# Question
Title: Simple way to post score from my game to Facebook and Twitter?
What's the best and simple way to post score from my game to Facebook and Twitter with store link in cocos2d-x?

# Answer
Twitter has a developer portal, where you'll probably want to check out the REST API. Specifically the POST statuses/update endpoint. Because this API is HTTP-based, you'll need a way to make such requests from your game. This question on SO addresses that subject, with suggestions such as curlpp.

Facebook has a similar set of APIs available, described on their developer portal. Unfortunately most of their actual documentation is behind a Facebook login wall, so I won't link it directly. But if you search for "facebook api post to wall" you get several results, including direct links to the graph API documentation for posting and this SO question.

Facebook has JavaScript, Objective-C and Java-based APIs.
> 1 votes

---
Tags: c++, android, facebook, cocos2d-x, twitter
---


# Question
Title: How to define 648 units, with 22 different values in Java
A friend and I are currently looking at developing a game. We have 648 units that need to be defined, with 22 final values.

To define the units in the game, we've created an abstract class with 44 variables and two methods. For example, if I encounter this unit in the game, I would pass a method its value, and it would look at some sort of lookup table which give all these base, final values. The problem we've encountered is finding a method of doing this effectively, and securely.

For now I have a few units defined through enumeration, and have their values stored in an array. My partner suggested to create a defining class with a plaintext lookup table. However, I see the problem with such a solution would either be the length, or quantity of lookup tables. I have searched around, but most solutions entail the use of a server. Our current goal is to just release an offline client with everything already defined.

Does anyone have any suggestions on how to store 648 units with 22 different final attributes effectively, so that such an entity could be called later and examined?

# Answer
> 8 votes
Read in the data from a file. 648 lines of data, one line per unit type. Store that into an array of 648 unit prototypes. Either write the data by hand, or write a tool for it. You might consider writing the values in Excel and exporting a CSV file. (parsing suggestions here.)

Once you have the data in memory as an array of unit prototypes, making units is easy. Create an uninitialised unit instance, look up the relevant unit prototype in the array, and copy the 22 values across.

---
Tags: java, databases
---


# Question
Title: Rotate 3D cube so nearest side is facing user
How do I figure out the new angle and rotation vectors for the most visible side of the cube?

Why: The user can rotate cube, but when finished I'd like the cube to snap to a side facing the user.

What: I'm currently using CoreAnimation in iOS to do the rotation with CATransform3D. I have the current angle and the rotation vectors so I can do this:

```
CATransform3DMakeRotation(angle, rotationVector[0], rotationVector[1], rotationVector[2]);

```

Additional Info: I'm currently using Bill Dudney's Trackball code to generate movement and calculate angle and rotation vector.

# Answer
To find the 'most visible side' of the cube, take dot products of the cube's X, Y, and Z axes with the 'look vector' - that is, the direction the camera is looking; the axis with the largest absolute dot product will be the axis most aligned with that vector, and the sign indicates which of the two faces along that axis ('positive' or 'negative') is facing the viewer. For instance, assuming you have your cube defined from (-1, -1, -1) to (+1, +1, +1), then dot products of -0.25, 0.3, and -0.92 would mean that the Z faces are most aligned with the view; whether that's the face z=-1 or the face z=1 depends on your particular conventions (e.g., whether positive Z goes into or out of the screen).

Note that this doesn't give you enough information to fully snap the cube into place, though - for that, you'd need not just the side of the cube facing the viewer but also the side of the cube facing in some orthogonal direction - for instance, which side of the cube is facing rightwards. You can find that using the same general idea, only dotting with (the worldspace transformation of) your screenspace X axis instead of Z (which is the look vector).

Once you have these two faces (or equivalently, the two axes - e.g., (0, 0, -1) and (1, 0, 0)), you can cross them to find your third 'aligned axis'; that's enough to give you an orientation matrix, and you can then Slerp from your current orientation to this target orientation. There are a couple of gotchas to be aware of with this approach - specifically, you have to be careful about how you handle ties to make sure that you never accidentally assign the same faces to your 'facing the viewer' and 'facing right' axes.
> 9 votes

# Answer
So, you have two problems you're trying to solve?

1. Determining the "most visible side of the cube."
2. Pointing that side at the camera.

Off the top of my head, if you were to determine the distances from the 8 vertices of the cube from the camera's location, the 4 least distances represent the quad that's mostly facing the camera. (There's probably a better way to do it but I'm not great a linear algebra.)

To point at the camera, align the surface normal of that cube face with a line from the center of the cube to the camera. (Or something similar constructing a LookAt matrix.)
> 0 votes

---
Tags: 3d, mathematics, ios
---


title: Scroller game level map advice

text:
# Question
Title: Scroller game level map advice
I'm started a XNA project to make a game similar in gameplay to Super Spy Hunter on a NES, which is used as a feature reference. The first thing I thought of is how to store and display level. Currently I'm thinking of using some tile graphics editor and custom pipeline for drawing level. I'm not sure however, that all is possible to implement every feature of reference game, but at least it's a start.

Question is, looking at a given gameplay video, can you think of any possibly better approach then to design level using a tiles?

By "better approach" I mean which will be either easier to work with, which will be more "natural" for this kind of game. The doubt comes mainly from a huge technology gap between then (1990) and now. So there is possibility that using current cpu power this could be done easier.

**Update 1**. As I continue study reference game and @ashes999 correctly mentioned procedural generation also comes into my mind. I began to think game logic is something like (simplified):

```
while next road section exist:
    get road section data;
    set road generation options (borders type, road type, etc);
    set road section lenght;
    while not end of a section:
        generate road;
        apply pseudorandom eye candy stuff;

```

this all looks like a pretty good data driven algorithm.

# Answer
> 1 votes
In a word: PCG (procedurally generated content). Procedurally generate the level; this allows you to create "infinite" length as needed by the user.

What does PCG mean?

In your context, PCG means: only create as much of the map as necessary (maybe 10 screens worth or something ahead of the user). When you "run out" of road, recreate more.

The content is generated algorithmically. Looking at the video you posted, I would just randomly generate the width of the road; that's it. Generate enough ahead compared to what you need.

It's really simple, and flexible; you get "infinite" road.

# Answer
> 2 votes
It is a very hard work to create such a long map with tiles. I propose a "better" solution:

* The border of ther road is series of line sections, you can render render poligons with texture. It is quite simple. The road can be filled with textured poligons.
* The background (water, grass, etc) is just simple texture, you can just address the map based on the position where they start (or end). You need to create a screenspace rectangle, covered by the texture, and shift it slightly. At the borders, you can create two of these rectangles, and align them accordingly.
* The large background elements (houses, bridges, etc) can be added as big objects, with custom rectangles. Since they have no other purpose, just decorating the background, they are just freely positioned spritest, textures (or models)

For the foreground, you can use address the enemies, and other objects based on their positions on the map.

This solution is also good for 3D but you need a bit trick for the road part, the rest is almost the same.

Advantages:

* Border: You only stores line segments, which is independent of the lenght of the segments, and you can freely edit the map easily. And the border line can be even used for collision detection.
* Background: Tiles takes larger data, and more time to set. As you can see, in the gameplay, there is a lot of water. Instead of setting a few thusand tiles, you just store a texture name and a value of the beginning (mesured in distance from the beginning. E.g. WATER 0, GRASS 200, WATER 500, etc... Of course, you use some structure and an array/list to store them, but it is much less data then the tiled version.
* Buildings: Each building covers a whole bunch of tiles, which are closely related (you dont want to put a single wall tile in anywhere else). It is obviously less data, than the tiled ones, and can be easily moved.

---
Tags: xna, architecture, level-design
---


# Question
Title: Resolution problems when porting a Unity game to Android
So, I'm porting a game to the Android for the first time in Unity3D. And I've run in to a few problems along the way. My current problem is the resolution doesn't seem to be right, it cuts off the edges of the screen and my scrolling stops for scrolling the screen left/right are no longer in the right place.

After doing a bit of research, a lot of people say you need to make your game Resolution Independent to be able to run on all Androids/Iphone/Ipad. Is this true? If so, how do I go about doing that? If not, how can I help fix the resolution so when I port to mobile devices it looks right?

EDIT: I still don't really have what I need, resolutions still aren't working properly even with the code and tricks listed below. I need some way for the resolution to adjust based on the device. For some reason when I try to retrieve the resolution of a device using Mungoid's code it returns 0x0

# Answer
A problem you'll run into with Android is that every different device has its own screen size, resolution, and pixel density. If you want your game to look identical on all devices, you're in for *a lot* of work and will probably never be pleased with the results. Either the game will appear stretched on widescreen displays or compressed on non-widescreen ones. I suggest you decide what's truly important and let anything else slide a little.

Without any screenshots or knowledge of what your game is and what it looks like, we can all speculate solutions but we don't have specific direction to give you specific counsel.

In Unity, you can access the dimensions of the current screen with the Screen class: `Screen.width` and `Screen.height` (among other properties). You could then change the Camera's aspect ratio to change what is visible on your different sized screens based on the screen dimensions and your personal expectation of what should be visible.

If you need to ensure any HUD displays are scaled properly, you can do that by changing the GUI transform matrix based on the screen's dimensions in every `OnGUI()` function. I've done it before by making this simple script and attaching it to anything that rendered GUI elements I wanted scaled:

```
//GUI values in code are assigned based on an 800x600 screen
private var nativeWidth : float = 800.0f;
private var nativeHeight : float = 600.0f;
private var guiMatrix : Matrix4x4;

function Start ()
{
    var scale : Vector3 = Vector3(Screen.width / nativeWidth,
                                  Screen.height / nativeHeight,
                                  1.0f);
    guiMatrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, scale);
}

function GetGUIMatrix() : Matrix4x4
{
    return guiMatrix;
}

```

Then, in the actual `OnGUI()` function(s), I set the transform matrix right away:

```
function OnGUI()
{
    GUI.matrix = guiScale.GetGUIMatrix();
    /* Everything Else */
}

```
> 7 votes

# Answer
you could try something like the following and apply it. I would guess that a mobile device should only return one resolution.

```
function Start()
{
    var resolutions : Resolution[] = Screen.resolutions;
    // Print the resolutions
    for (var res in resolutions) {
        print(res.width + "x" + res.height);
    }
    // Switch to the lowest supported fullscreen resolution
    Screen.SetResolution (resolutions[0].width, resolutions[0].height, true);
};

```

Also take a look here for more info about the Screen in unity http://unity3d.com/support/documentation/ScriptReference/Screen.html
> 0 votes

---
Tags: c#, android, unity, resolution
---


title: Nested Sprite Batch and background draw

text:
# Question
Title: Nested Sprite Batch and background draw
my code looks something like this:

```
        graphicsDevice.Clear(Color.Black);
        spriteBatch.Begin();
        spriteBatch.Draw(contentLoader.VerticalGradient, tileSafe, null, Color.DarkGreen, 0, Vector2.Zero, SpriteEffects.None, 0.5f);

// snip a lot, including drawing stuff on the sprite batch.

        // create a new sprite batch (for snipping)
        var initialViewport = InitialBatch.GraphicsDevice.Viewport;
        InitialBatch.GraphicsDevice.Viewport = new Viewport(displayRectangle);
        var newBatch = new SpriteBatch(InitialBatch.GraphicsDevice);
        newBatch.Begin();

// draw stuff on the new batch

        newBatch.End();
        InitialBatch.GraphicsDevice.Viewport = initialViewport;

// more stuff on the original batch

        spriteBatch.End();

```

My problem is the third line of code I just added. I want to have a "background" on what I'm drawing (so it's not just black). So I draw it first.

Before I added that third line, everything worked great. But when I added it, everything drawn on the new/inner batch doesn't get displayed. If I draw it all on the normal sprite batch, it gets drawn (but doesn't get snipped properly), if I remove the drawing of the new texture, then the inner spritebatch works fine.

**Additional things I've tried**

I've tried moving the depth of the "background" texture, and when I do, it either makes the background disappear, or it makes the inner sprite batch stuff disappear. I want both.

Is there any way I can get both? Am I making sense? Is this inner sprite batch thing just crazy? I thought I used a standard example to do snipping, but maybe I got lucky and stumbled upon something crazy that just happens to work?

# Answer
> 3 votes
It won't work like you expect it to too, cause you assume your "inner" sprite batch will be drawn "inside" your "outer" spritebatch, but this is not the way SpriteBatch works. Your "inner" SpriteBatch will be finalized when you call End(). Your "outer" SpriteBatch calls End() after your "inner" SpriteBatch so it draws *over* your "inner" SpriteBatch and you see nothing.

Or another way to see it: There is no concept of an "inner" SpriteBatch as far as i know of. Every SpriteBatch you create inside another SpriteBatch is just that, another new SpriteBatch, could just as well be created "outside". What counts is the order of your End() calls.

This should work for you:

```
    graphicsDevice.Clear(Color.Black);
    spriteBatch.Begin();
    spriteBatch.Draw(contentLoader.VerticalGradient, tileSafe, null, Color.DarkGreen, 0, Vector2.Zero, SpriteEffects.None, 0.5f);
    spriteBatch.End();

    var newBatch = new SpriteBatch(InitialBatch.GraphicsDevice);
    newBatch.Begin();
    // draw your stuff
    newBatch.End();

```

However you should create your second SpriteBatch in LoadContent(), not in Draw(), as it costs time. Also, as noted in the comments, you could draw everything in one SpriteBatch using various techniques.

---
Tags: xna, spritebatch
---


# Question
Title: Problem with HLSL :TextureCoordinate0 is missing
I'm trying to create a very simple game, and am working with HLSL. I got this error in my draw method:

> The current vertex declaration does not include all the elements required by the current vertex shader. TextureCoordinate0 is missing.

Here is my draw method:

```
public void Draw(Matrix View, Matrix Projection,Vector3 CameraPosition)
{
        // Calculate the base transformation by combining
        // translation, rotation, and scaling

        Matrix baseWorld = Matrix.CreateScale(Scale) *
            Matrix.CreateFromYawPitchRoll(Rotation.X, Rotation.Y, Rotation.Z) *
            Matrix.CreateTranslation(Position);
        foreach (ModelMesh mesh in Model.Meshes)
        {
            Matrix localWorld = modelTransforms[mesh.ParentBone.Index] * baseWorld;

            foreach (ModelMeshPart part in mesh.MeshParts)
            {
                Effect effect = part.Effect;
                if (part.Effect is BasicEffect)
                {
                    ((BasicEffect)effect).World = localWorld;
                    ((BasicEffect)effect).View = View;
                    ((BasicEffect)effect).Projection = Projection;
                    ((BasicEffect)effect).EnableDefaultLighting();
                }
                else
                {
                    setEffectParameter(effect, "World", localWorld);
                    setEffectParameter(effect, "View", View);
                    setEffectParameter(effect, "Projection", Projection);
                    setEffectParameter(effect, "CameraPosition", CameraPosition);

                    Material.SetEffectParameters(effect);
                }
            }
            mesh.Draw();
        }

```

But in `VertexShaderFunction (in LightingEffect)`, instead of `output.UV = input.UV` I put `output.UV=float2(somefloat,somefloat)` I get no error.

There is a another thing, I got this error when I try to load my "Cathedral" model and others, but for "teapot" model I get no error.

Here is my complete code and models.

# Answer
The problem is that your vertex buffer's data doesn't contain a channel for texture coordinates, and your shader requires it. You have to edit your model and add proper UV mapping to it.
> 2 votes

---
Tags: xna, hlsl
---


title: Promoting a Browser Game?

text:
# Question
Title: Promoting a Browser Game?
I have a new browser based game that I've worked on for a few months. Obviously all that effort goes to waste if no one sees it.

I know there's topics to do with games promotion, but browser games are a different field entirely.

How can I promote my browser game?

# Answer
> 18 votes
Have a look at some similar questions under the marketing tag.

Here are some things to do:

1. Make the game worth playing (see comment)
2. Get friends, family, colleagues, anyone to play it and tell people about it. This kicks off your initial word of mouth campaign.
3. Social media. Facebook site, twitter account, blog, there are loads now. This will increase the visibility of your game and start organic growth.
4. Incentivise playing if possible. Do you offer in-game credit/coins/points etc.? Give your first set of users a bonus for playing.
5. Incentivise word-of-mouth. Give your players an in-game (or other) bonus for bringing people to your game.
6. Targeted Adwords. If you have a budget, great! Target google and facebook users with keywords, etc.
7. Link-sharing. Forums and game blogs will have link-sharing schemes. You promote someone else's site, someone else promotes yours.
8. Tell people about it. You can do this without spamming. For example, you could add a comment under your question with a link to the game. I'd have a look and who knows - I might like it and tell people about it. Be wary though - you need to be considerate of how much you "push" your game in this way.
9. Submit your game to review sites. You get good feedback and linked traffic.
10. Create a community for your game. Not only will these guys tell you about bugs and suggest features, they'll also become evangelists for your game. (added May 15)
11. Read and apply lessons from The Zero Budget Indie Marketing Guide. (added May 19)

I'll add more when I think of some but hopefully this should be some good initial food for thought.

---
Tags: marketing, browser
---


# Question
Title: How do I sync multiplayer game state more efficiently than full-state updates?
I've done a little game network coding before, but primarily with TCP for games without real-time needs. I am working on a 2D Java game with networked multiplayer. For learning, I want to do this myself, without an existing network API.

How do I efficiently represent the game state sent to clients from a server? There is the most obvious but probably least efficient way, which would be to create some sort of game state context object with each player's location, animation state, etc., and send that out to each player *every update*. That doesn't seem terribly difficult to implement, but would probably be too large to achieve anything close to real-time interaction (of course my experience with this is limited so I may be incorrect).

Is there a solid way any of you have used before to only transmit changes in state, and is there even a large enough disparity in performance that it is worth the extra work?

# Answer
> 12 votes
Transmitting the full game state regularly is *usually* not feasible, though it does depend a lot on the complexity of you game. For a simple game with a small world model it may work.

I've personally had much more success with the following model:

* Game state stored in a well defined object model in a spatial data structure (e.g. an octree)
* All changes to game state (whether on the client or the server) are described as events. An event might be a property change on a game object, a change to a map tile, the movement of a game object etc.
* The game engine on the server produces a stream of events as the game proceeds. These are directly applied to the server's game state.
* The events are also sent to players, but *only if* the event is relevant to that player (e.g. is the event visible from the current position?)
* Changes in player visibility may also result in events to "reveal" new parts of the map etc when the player moves. This can also be used to ensure that the player gets an accurate initial view of the relevant game state when they first join the game.
* The game state for the player is updated with whatever events it receives. As such it only has a partial model of the game state, but it should stay in sync with the server assuming all events are correctly processed

This has provided good performance for me with even quite large game worlds.

Another tip, let the client take care of animation, particle effects etc. without reference to the server. There's no point transmitting these - they just need to be "triggered" by the appropriate game events.

# Answer
> 7 votes
The synchronization is usually split into two part: incremental and absolute.

Sometimes you must transmit everything, it is large, but if you pack it the right way you can do this once every few seconds. It is good to put everithing in place, correcting the faults of incremental refreshes.

To achieve real-time experience, you must transmit some changes fast, but only the attributes that can change. For example if a rocket flies in a straight line, you needn't to update the position, each client can calculate it from the starting point. But when it hits, you may generate a message about it, so each client can explode the rocket in the right place. Minor glitches can be ignored.

Of course you only update stuff, when they can influence the client! Something far off the screen is not worth it. Some values can be updated less frequently. For example the positions are important to be more or less precise, events (death, shot fired, explosion, etc) must be sent instantly, while not directly important values can have lower refresh periods, for example scoreboard, chat.

The packing of data is also important. You can transmit approximately 1400 bytes (configuration dependent, this is the default) in one UDP package, usually there is a few bytes of header. So you can update 50-100 unit positions in one package easily.

# Answer
> 1 votes
Depending on your game, you might consider a "synchronized execution" model where each client happens to play the same game by simply sharing non-deterministic inputs like keyboard/joystick inputs and timer events. (As compared to a model where each client runs local simulations and expects to integrate results from remote simulations). Your game engine generally needs to be fully deterministic for this to work, which can be a heavy burden depending on the game. But if the game is already deterministic, this may be an easier approach.

This #AltDevBlogADay post covers some aspects of this approach in a modern RTS (specifically how to detect when your clients start running "different" games.)

Remember to keep it simple until proven otherwise, though. :)

---
Tags: networking, multiplayer, synchronization, efficiency, game-state
---


title: Atmospheric Scattering

text:
# Question
Title: Atmospheric Scattering
I'm trying to implement atmospheric scattering based on Sean O\`Neil algorithm that was published in GPU Gems 2. But I have some trouble getting the shader to work.

I've downloaded sample code of O\`Neil from NVidia site. Made minor adjustments to the shader 'SkyFromAtmosphere' that would allow it to run in AMD RenderMonkey.

In the images it is see-able a form of banding occurs, getting an blueish tone. However it is only applied to one half of the sphere, the other half is completely black. Also the banding appears to occur at Zenith instead of Horizon, and for a reason I managed to get pac-man shape.

I would appreciate it if somebody could show me what I'm doing wrong.

Vertex Shader:

```
uniform mat4 matView;
uniform vec4 view_position;
uniform vec3 v3LightPos;

const int   nSamples = 3;
const float fSamples = 3.0;
const vec3  Wavelength = vec3(0.650,0.570,0.475);

const vec3  v3InvWavelength = 1.0f / vec3( Wavelength.x * Wavelength.x * Wavelength.x * Wavelength.x,
                                           Wavelength.y * Wavelength.y * Wavelength.y * Wavelength.y,
                                           Wavelength.z * Wavelength.z * Wavelength.z * Wavelength.z);

const float fInnerRadius = 10;
const float fOuterRadius = fInnerRadius * 1.025;
const float fInnerRadius2 = fInnerRadius * fInnerRadius;
const float fOuterRadius2 = fOuterRadius * fOuterRadius;
const float fScale = 1.0 / (fOuterRadius - fInnerRadius);
const float fScaleDepth = 0.25;
const float fScaleOverScaleDepth = fScale / fScaleDepth;
const vec3  v3CameraPos = vec3(0.0, fInnerRadius * 1.015, 0.0);
const float fCameraHeight = length(v3CameraPos);
const float fCameraHeight2 = fCameraHeight * fCameraHeight;

const float fm_ESun  = 150.0;
const float fm_Kr    = 0.0025;
const float fm_Km    = 0.0010;
const float fKrESun = fm_Kr * fm_ESun;
const float fKmESun = fm_Km * fm_ESun;
const float fKr4PI = fm_Kr * 4 * 3.141592653;
const float fKm4PI = fm_Km * 4 * 3.141592653;

varying vec3 v3Direction;
varying vec4 c0, c1;

float scale(float fCos)
{
   float x = 1.0 - fCos;
   return fScaleDepth * exp(-0.00287 + x*(0.459 + x*(3.83 + x*(-6.80 + x*5.25))));
}

void main( void )
{
   // Get the ray from the camera to the vertex, and its length (which is the far point of the ray passing through the atmosphere)
   vec3 v3FrontColor = vec3(0.0, 0.0, 0.0);
   vec3 v3Pos = normalize(gl_Vertex.xyz) * fOuterRadius;
   vec3 v3Ray = v3CameraPos - v3Pos;
   float fFar = length(v3Ray);
   v3Ray = normalize(v3Ray);

   // Calculate the ray's starting position, then calculate its scattering offset
   vec3 v3Start = v3CameraPos;
   float fHeight = length(v3Start);
   float fDepth = exp(fScaleOverScaleDepth * (fInnerRadius - fCameraHeight));
   float fStartAngle = dot(v3Ray, v3Start) / fHeight;
   float fStartOffset = fDepth*scale(fStartAngle);

   // Initialize the scattering loop variables
   float fSampleLength = fFar / fSamples;
   float fScaledLength = fSampleLength * fScale;
   vec3 v3SampleRay = v3Ray * fSampleLength;
   vec3 v3SamplePoint = v3Start + v3SampleRay * 0.5;

   // Now loop through the sample rays
   for(int i=0; i<nSamples; i++)
   {
      float fHeight = length(v3SamplePoint);
      float fDepth = exp(fScaleOverScaleDepth * (fInnerRadius - fHeight));
      float fLightAngle =  dot(normalize(v3LightPos), v3SamplePoint) / fHeight;
      float fCameraAngle = dot(normalize(v3Ray), v3SamplePoint) / fHeight;
      float fScatter = (-fStartOffset + fDepth*( scale(fLightAngle) - scale(fCameraAngle)))/* 0.25f*/;
      vec3 v3Attenuate = exp(-fScatter * (v3InvWavelength * fKr4PI + fKm4PI));

      v3FrontColor += v3Attenuate * (fDepth * fScaledLength);
      v3SamplePoint += v3SampleRay;
   }

   // Finally, scale the Mie and Rayleigh colors and set up the varying variables for the pixel shader

   vec4 newPos = vec4( (gl_Vertex.xyz + view_position.xyz), 1.0);
   gl_Position = gl_ModelViewProjectionMatrix * vec4(newPos.xyz, 1.0);
   gl_Position.z = gl_Position.w * 0.99999;
   c1 = vec4(v3FrontColor * fKmESun, 1.0);
   c0 = vec4(v3FrontColor * (v3InvWavelength * fKrESun), 1.0);
   v3Direction = v3CameraPos - v3Pos;
}

```

Fragment Shader:

```
uniform vec3 v3LightPos;
varying vec3 v3Direction;
varying vec4 c0;
varying vec4 c1;

const float g =-0.90f;
const float g2 = g * g;
const float Exposure =2;

void main(void){
   float fCos = dot(normalize(v3LightPos), v3Direction) / length(v3Direction);
   float fMiePhase = 1.5 * ((1.0 - g2) / (2.0 + g2)) * (1.0 + fCos*fCos) / pow(1.0 + g2 - 2.0*g*fCos, 1.5);
   gl_FragColor = c0 + fMiePhase * c1;
   gl_FragColor.a = 1.0;
}

```

# Answer
You might want to take a look at this source code which does the same thing for osgEarth.
> 1 votes

---
Tags: opengl, mathematics, shaders, special-effects, debugging
---


# Question
Title: What are some good resources for building a voxel engine?
What are some good resources (tutorials, code, papers, etc.) for learning about voxel rendering?

# Answer
> 16 votes
I recently did some experimentation with voxels for rendering terrain, with support for overhangs. I pretty much used these articles to build my prototype:

Something to look out for, I could never get normal generation to work correctly once I had generated a mesh from my voxels. If anyone can give any pointers for this, I'd be grateful.

# Answer
> 8 votes
Here is a 10 year old tutorial that goes pretty deep into Voxel rendering as a technology. It's still a good read.

# Answer
> 5 votes
This paper by Jon Olick is pretty interesting: http://s08.idav.ucdavis.edu/olick-current-and-next-generation-parallelism-in-games.pdf

And those two forum threads about it: http://ompf.org/forum/viewtopic.php?f=3&t=904

and: https://mollyrocket.com/forums/viewtopic.php?t=551

It gives you a nice overview about how things could be done in a modern voxel engine.

# Answer
> 2 votes
I work on an open-source voxel library called PolyVox which has some good documentation for the technology. Also linked at the bottom of our documentation page is a chapter of 'Game Engine Gems Volume 1' on volumetric representations in games via Google Books.

# Answer
> 2 votes
Check this Stackoverflow post for links to Voxel libraries.

I'm also developing a renderer based on voxel raycasting.

I developed an out-of-core voxelizer and SVO builder and published paper and code here.

---
Tags: voxels
---


# Question
Title: Is developing for non-retina iPod Touch/iPhones still worth it for deployment?
We're a couple of guys making games for iPod Touch and iPhone. I personally have an iPhone 4 with the retina display and I'll be using this as my main test device. I have an opportunity to purchase a cheap 2nd generation non-retina iPod Touch and was thinking that would be good to have as another test device. But is it worth the purchase?

There is still a huge amount of people on non-retina hand devices? Is a 2nd generation iPod Touch just too old to worry about and maybe I should look into getting a new generation?

# Answer
The iPhone 3GS is just as capable as the 4 (armv7, ogles2, latest iOS software) and there are a decent number of them out there. I don't think there's any way to prevent those devices from seeing your game in the store so unless you want the occassional bad review I'd try to support them.

http://en.wikipedia.org/wiki/List\_of\_iOS\_devices
> 5 votes

---
Tags: iphone, ios, testing, deployment
---


# Question
Title: Why are the "professional" versions of console SDKs closed to the public?
Why are the "professional" versions of console SDKs closed to the public? For example the Xbox Development Kit is available only to certain registered developers. The PS3 has some similar arrangement. Even the pricing is undisclosed.

What is the reason for this secrecy? Also, what additional features do these "professional" SDKs have, in comparison with the free SDKs (like XNA)?

# Answer
> 18 votes
This scheme was started by Nintendo to counter the effects of the video game crash of 1983.

> There were several reasons for the crash, but the main cause was supersaturation of the market with hundreds of mostly low-quality games which resulted in the loss of consumer confidence....
>
> In 1986, Nintendo president Hiroshi Yamauchi noted that "Atari collapsed because they gave too much freedom to third-party developers and the market was swamped with rubbish games." In response, Nintendo limited the number of titles that third-party developers could release for their system each year.

It continues today because it's a lucrative deal for console manufacturers, allowing them to sell devices below-cost to customers, and make money licensing the SDK to developers, often taking a cut of revenue as well. The benefit to consumers today is highly questionable, especially compared to more-open-but-still-gated models like Apple's App Store.

The difference between the free and proprietary SDK varies by vendor. In all cases, the free option is more technologically limited - XNA limits you to C#, for example, where the full XDK allows you to write in any language that can target the Xbox 360's PPC-based architecture. The same is true of the hardware. The Xbox debugging units contain larger hard drives, can connect to SMB drive shares, and connect to a special version of Xbox Live. They usually also come with customer support contracts and access to other developer tools like better profilers or test harnesses.

# Answer
> 4 votes
Well for one thing these professional SDKs usually come with different hardware. For example this is how (the old) PS3 development station looks like (U2/U3 rack size):

And this is a Xbox 360 development kit:

And even if the SDKs can run on normal 'consumer' consoles (which they can do but with limited functionality, usually just used for debugging) it still possesses a security risk since the SDKs gives you a lot lower level access.

There is one more thing: how broader you distribute the tools how more polished and easier to support it should be. Software like XNA is extremely polished and an amateur can easily make heads or tails of it without reading a lot of the documentation. Time till you first polygon on screen: 5 minutes. The SDKs are a lot less friendly beasts you'll be reading documentation for days or weeks before you can get anything going and special engineers are sometimes flown in to studios to help with quirks. The support cost per person is a lot higher so Microsoft and Sony try to limit the number of people who they have to support to the people they know can make a good profit for them. It's all about costs and benefits.

---
Tags: game-industry, console
---


title: 3D: How how handle like 500 NPC

text:
# Question
Title: 3D: How how handle like 500 NPC
I'm currently working on a 3D game. My game have like 10 NPC's and a really small world. But if I want to have a larger world with lots of NPC's? I think it's not a good idea to update and check collision with NPC's that is far far away from the hero.

So any tip on how to handle things that are outside the hero's sight.

# Answer
Two basic optimizations

1) Dividing you world into logical *chunks*. A chunk is a rather large portion of your game world and independent of your actual objects. It is large enough that you can make the simple assumption: You have 2 "collidable" objects, one is in chunk A, the other in chunk B. If A and B do not have a common edge or point, then the said objects cannot possibly collide, so they have a distance of 2 chunks or larger. Then you can disregard them right away. Note that if you use hexagonal chunks, you only have to check for common edges, i.e. you can use a hex-based equivalent to the "Manhattan distance".

2) Distance-based pruning. If the 2 objects in questions are in the same chunk, or in adjacent chunks, you need to refine the check. At the simplest level, imagine a sphere centered around every object that can collide with something else. The sphere is just large enough to completely surround its object, so that neither part of the object can stick out under any circumstances. Then you can conclude that if the distance between 2 objects is larger than the sum of both spheres' radius, then those 2 objects cannot have collided. To optimize this calculation, don't work with distance and sum of radii, but their squares, to avoid calculating expensive square roots.

Only when both checks indicate a possible collision, move on to the more expensive checks, which is probably hit boxes. Remember that the closer your bounding boxes resemble your actual object's geometry, the more expensive things get. You have to find a good compromise between quality and quantity of collision checks, but that depends on your game design entirely.
> 2 votes

# Answer
You should probably use a octree (see this question on StackOverflow) - don't worry about figuring out what is out of sight because would likely be more expensive than an octree.

This article explains how to use a quadtree (2D analogue of a octree) which should help demonstrate the concept. You might also find this page useful.
> 2 votes

# Answer
For the collisions you'll want to do *spatial hashing*. What that means is that you basically subdivide the world into several small parts where it's guaranteed that things within a "chunk" of the world cannot collide with anything not in it's chunk, or possibly a chunk next to it.

What you could also do is to freeze the NPC's when you're not near their chunk. This can probably be a good solution depending on how your game works. Doing something like this assumes that you, instead of looping through all game entities in a loop, construct an "update" method for the chunks themselves. That method in turn calls the update method on the entities. This way you can easily implement this method of splitting up into chunks.
> 1 votes

# Answer
You don't really have to apply physics and collision in NPCS, unless they're truly dynamic (Like one NPC that's on the player team, one npc that fights, etc.). Why? NPCs are already controlled by the program, so they should know where they can walk, where's the floor... So instead of:

```
Walk Forward;
Keep applying physics every frame to make it bound to the terrain;

```

You can just do once:

```
Walk forward at terrain level;

```

This can be hard if your terrain is irregular. But shouldn't be a VERY hard problem. Another solution is applying physics just when they're making some action like walking, then when you got it's final position just de-attach its body from the physics engine til it need to make another action.
> 0 votes

---
Tags: 3d, collision-detection
---


# Question
Title: Communicating between simulation and rendering in RTS
I've been creating an RTS game, and I'm a little unsure about how to deal with the above. Right now, I wish to control which units are visible to which players, and I've run into a little problem. Previously, I had three components- render, sim, and UI (untrusted scripted component). However, I'm beginning to believe that this is not the optimal architecture.

For example, given the task that only the relevant units should be visible from a given player's perspective, none of the above components are up to the job. The sim is player-independent, the renderer has no idea about players at all, and the UI can't be trusted. So I've come to the need to introduce a fourth component- a kind of Controller which communicates between the three components and correctly limits the information each one has access to.

Is this the normal approach? Or am I missing a trick when it comes to making the sim, UI, and renderer co-operate?

# Answer
> 2 votes
> Right now, I wish to control which units are visible to which players

So you're making a multiplayer game? Then "what can the player see" is an issue of the server distributing information properly. The client is just a rendering engine that displays everything that the server tells it about. There's literaly no connection between simulation and rendering. If the client has any simulation code (prediction code to account for lag or something) then it should work only on the information that the player can have anyway.

There probably could be some optimatlizations logic for each client that would describe what you can and cannot possibly see in the chunk that the camera currently is in (for example you don't have to display chunks that are behind the camera and you don't have to display chunks that are behind a huge mountain), but TBH this seems like a regular issue that's solved with frustum culling or some other forms of culling. There's plenty of articles these kinds of optimalizations.

# Answer
> 0 votes
I don't see why the sim is 'player independent' - it may be shared across all players, but surely that is the part of the game that decides what each player is able to see. The renderer can get its information from there.

---
Tags: c++, rts
---


title: C# XNA 4.0 Rectangle Rotation Collision

text:
# Question
Title: C# XNA 4.0 Rectangle Rotation Collision
I can easily rotate my sprite, but how could I rotate my rectangle for my collision (thinking of using the Separating Axis Theorem, But I have no clue how to apply it). Help or an example would be appreciated.

**Game1 Class:**

```
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace CombatTank
{

public class Game1 : Microsoft.Xna.Framework.Game
{
    //Declare Graphic Manager & Spritebatch
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;

    //Declare Player 1
    theBody player1TankBody;

    //Declare Player 2
    theBody player2TankBody;

    //Save Player 1 Position
    Vector2 savedPlayer1TankBodyPosition;

    //Save Player 2 Position
    Vector2 savedPlayer2TankBodyPosition;

    //Declare Keyboard States
    KeyboardState currentkeyboardState;
    KeyboardState previousKeyboardState;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
    }

    protected override void Initialize()
    {
        //TankBody Position Player 1
        Vector2 player1TankBodyPosition = new Vector2(200, 200);
        Vector2 player2TankBodyPosition = new Vector2(400, 200);

        //TankBody Scale
        float player1TankBodyScale = 1.0F;
        float player2TankBodyScale = 1.0F;

        //TankBody Rotation
        float player1TankBodyRotation = 0.0F;
        float player2TankBodyRotation = 0.0F;

        //TankBody Color
        Color player1TankBodyColor = Color.Red;
        Color player2TankBodyColor = Color.Blue;

        //Create Tank
        player1TankBody = new theBody(player1TankBodyPosition,player1TankBodyScale, player1TankBodyRotation, player1TankBodyColor);
        player2TankBody = new theBody(player2TankBodyPosition, player2TankBodyScale, player2TankBodyRotation, player2TankBodyColor);

        base.Initialize();
    }

    protected override void LoadContent()
    {
        //Create New SpriteBatch
        spriteBatch = new SpriteBatch(GraphicsDevice);

        //Load The Player 1 TankBody Texture
        Texture2D player1SpriteTankBody = Content.Load<Texture2D>("TankBody");
        player1TankBody.LoadContent(Content,"TankBody");

        //Extract Collision Data For Player 1
        player1TankBody.TankBodyTextureData = new Color[player1TankBody.Texture.Width * player1TankBody.Texture.Height];
        player1TankBody.Texture.GetData(player1TankBody.TankBodyTextureData);

        //Load The Player 2 TankBody Texture
        Texture2D player2SpriteTankBody = Content.Load<Texture2D>("TankBody");
        player2TankBody.LoadContent(Content, "TankBody");

        //Extract Collision Data For Player 2
        player2TankBody.TankBodyTextureData = new Color[player2TankBody.Texture.Width * player2TankBody.Texture.Height];
        player2TankBody.Texture.GetData(player2TankBody.TankBodyTextureData);

    }

    protected override void UnloadContent()
    {

    }

    protected override void Update(GameTime gameTime)
    {
        //Save Player 1 Postion
        savedPlayer1TankBodyPosition.X = player1TankBody.Position.X;
        savedPlayer1TankBodyPosition.Y = player1TankBody.Position.Y;

        //Save Player 2 Position
        savedPlayer2TankBodyPosition.X = player2TankBody.Position.X;
        savedPlayer2TankBodyPosition.Y = player2TankBody.Position.Y;

        //Updates Player 1
        UpdatePlayer1(gameTime);

        //Update Player 2
        UpdatePlayer2(gameTime);

        //Collision Player 1
        CollisionPlayer1(gameTime);

        //Collision Player 2
        CollisionPlayer2(gameTime);

        base.Update(gameTime);
    }

    private void UpdatePlayer1(GameTime gameTime)
    {
        //Save the previous state of the keyboard
        previousKeyboardState = currentkeyboardState;

        //Read the current state of the keyboard
        currentkeyboardState = Keyboard.GetState();

        //TankBody Movement
        if (currentkeyboardState.IsKeyDown(Keys.W))
        {
            //Move Tank Forward
            player1TankBody.Position.X -= 5 * (float)Math.Cos(player1TankBody.Rotation);
            player1TankBody.Position.Y -= 5 * (float)Math.Sin(player1TankBody.Rotation);
        }
        if (currentkeyboardState.IsKeyDown(Keys.S))
        {
            //Move Tank Backwards
            player1TankBody.Position.X += 5 * (float)Math.Cos(player1TankBody.Rotation);
            player1TankBody.Position.Y += 5 * (float)Math.Sin(player1TankBody.Rotation);

        }
        if (currentkeyboardState.IsKeyDown(Keys.A))
        {
            player1TankBody.Rotation -= 0.03f;
        }
        if (currentkeyboardState.IsKeyDown(Keys.D))
        {
            player1TankBody.Rotation += 0.03f;
        }

    }

    private void UpdatePlayer2(GameTime gameTime)
    {
        //Save the previous state of the keyboard
        previousKeyboardState = currentkeyboardState;

        //Read the current state of the keyboard
        currentkeyboardState = Keyboard.GetState();

        //TankBody Movement
        if (currentkeyboardState.IsKeyDown(Keys.Up))
        {
            //Move Tank Forward
            player2TankBody.Position.X -= 5 * (float)Math.Cos(player2TankBody.Rotation);
            player2TankBody.Position.Y -= 5 * (float)Math.Sin(player2TankBody.Rotation);
        }
        if (currentkeyboardState.IsKeyDown(Keys.Down))
        {
            //Move Tank Backward
            player2TankBody.Position.X += 5 * (float)Math.Cos(player2TankBody.Rotation);
            player2TankBody.Position.Y += 5 * (float)Math.Sin(player2TankBody.Rotation);
        }
        if (currentkeyboardState.IsKeyDown(Keys.Left))
        {
            player2TankBody.Rotation -= 0.03f;
        }
        if (currentkeyboardState.IsKeyDown(Keys.Right))
        {
            player2TankBody.Rotation += 0.03f;
        }

    }

    private void CollisionPlayer1(GameTime gameTime)
    {

        if (IntersectPixels(player1TankBody.BoundingBox, player1TankBody.TankBodyTextureData, player2TankBody.BoundingBox, player2TankBody.TankBodyTextureData))
        {
            player1TankBody.Position.X = savedPlayer1TankBodyPosition.X;
            player1TankBody.Position.Y = savedPlayer1TankBodyPosition.Y;

        }

    }

    private void CollisionPlayer2(GameTime gameTime)
    {
        if (IntersectPixels(player2TankBody.BoundingBox, player2TankBody.TankBodyTextureData, player1TankBody.BoundingBox, player1TankBody.TankBodyTextureData))
        {
            player2TankBody.Position.X = savedPlayer2TankBodyPosition.X;
            player2TankBody.Position.Y = savedPlayer2TankBodyPosition.Y;

        }
    }

    static bool IntersectPixels(Rectangle rectangleA, Color[] dataA, Rectangle rectangleB, Color[] dataB)
    {
        //Find top Bound of the Rectangle
        int top = Math.Max(rectangleA.Top, rectangleB.Top);
        int bottom = Math.Min(rectangleA.Bottom, rectangleB.Bottom);
        int left = Math.Max(rectangleA.Left, rectangleB.Left);
        int right = Math.Min(rectangleA.Right, rectangleB.Right);

        for (int y = top; y < bottom; y++)
        {
            for (int x = left; x < right; x++)
            {
                //Get Color of both Pixels
                Color colorA = dataA[(x - rectangleA.Left) + (y - rectangleA.Top) * rectangleA.Width];
                Color colorB = dataB[(x - rectangleB.Left) + (y - rectangleB.Top) * rectangleB.Width];

                //Both pixel are not completely Transparent
                if (colorA.A != 0 && colorB.B != 0)
                {
                    //Then an intersection is found
                    return true;
                }

            }

        }

        //No Intersection
        return false;
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        spriteBatch.Begin();

        player1TankBody.Draw(spriteBatch);
        player2TankBody.Draw(spriteBatch);

        spriteBatch.End();

        base.Draw(gameTime);
    }
}
}

```

**theBody Class:**

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.Content;

namespace CombatTank
{
class theBody
{
    //TankBody Texture
    private Texture2D texture;
    public Texture2D Texture
    {
        get
        {
            return texture;
        }
    }

    //TankBody Height
    private float height;
    public float Height
    {
        get
        {
            return height;
        }
    }

    //TankBody Width
    private float width;
    private float Width
    {
        get
        {
            return width;
        }

    }

    //TankBody Position
    public Vector2 Position;

    //TankBody Origin
    public Vector2 Origin;

    //TankBody Rotation
    public float Rotation = 0.0F;

    //TankBody Color
    public Color Color = Color.White;

    //TankBody Scale
    public float Scale = 1F;

    //TankBody BoundingBox
    public Rectangle BoundingBox
    {
        get
        {
            return new Rectangle((int)Position.X, (int)Position.Y, (int)texture.Width, (int)texture.Height);
        }
    }

    //TankBody color Data(Used For Pixel Collision)
    public Color[] TankBodyTextureData;

    //TankBody Constructor
    public theBody(Vector2 position,float scale,float rotation, Color color)
    {
        Position = position;
        Scale = scale;
        Rotation = rotation;
        Color = color;
    }

    //LoadContent
    public void LoadContent(ContentManager contentManager, string assetname)
    {
        texture = contentManager.Load<Texture2D>(assetname);
        Origin = new Vector2(Texture.Width / 2, Texture.Height / 2);
    }

    //Draw
    public virtual void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(texture, Position, null, Color, Rotation, Origin, Scale, SpriteEffects.None, 0);
    }

    //Update
    public void Update(GameTime gameTime)
    {

    }
}
}

```

# Answer
SAT method of collision can be hard to implement if you don't know what is being accomplished when implementing it. This blog post helped me but I found many more explanations and examples on the internet to supplement myself. Being able to "apply" something and "control" something make all the difference when making fun games. I recommend that you take the time to understand the math before you attempt to implement it.

http://www.codezealot.org/archives/55
> 1 votes

# Answer
First of all, you should perform a distance-based pruning of possible collisions. A bounding rectangle around object O1 with a longer edge of length *a* has a potential collision radius R1 = sqrt(2) * *a*/2, so if another object O2 with collision radius R2 is more than R1+R2 apart, they cannot collide. Only if the collision circles intersect should you check for the more complicated rectangle collision. Work with squared values to avoid the expensive sqrt(), except if you need the actual distance anyway.

Then you need to change your BoundingBox property and collision detection method to support arbitrarily rotated rectangles. Instead of the Rectangle class, use 4 Points named UpperLeft, UpperRight, LowerLeft, LowerRight that you adjust according to the object's rotation. Then you use, as you already noted, the Separating Axis Theorem. Since you are using Rectangles, you can use a lot of optimizations. Details here, including Maths:

2D Rotated Rectangle Collision
> 0 votes

---
Tags: xna, collision-detection, rotation
---


# Question
Title: Anyone know of other unique playable archetypes?
Well I like to play games that give me a wide breath of options. For most part I see games implementing certain archetypes like the usual RPG trinity (tank, DPS and healer).

So far the most archetypes I've seen are in fighting, card and strategy games.

Fighting games archetypes I've seen are:

* Rush down (GG Accent Core Venom, Kof 2k1 heidern)
* Grappler (SF Zangief)
* Zoning (SF Dhalsim, KoF Billy Kane)
* Ranged(GG Dizzy)
* Trapper (GG testament)
* Well rounded (SF Ryu)
* Status effects (GG Baiken)
* Chance (GG Faust)
* Counter (GG Baiken)
* Time (Arcana Heart Anutpada, Psychic force Wong, Jojo's Bizarre adventure Dio)
* Positions control (Arcana Heart Dieu Mort).

Card Games: Burn, milling, OTK, counter, graveyard based, trapping (Yu-gi-oh), remove from play, restrict.

Strategy games: League of legends have a number of them so I'll just link to their wiki. Note not all are archetypes though, add to that builders as well.

So any other that you guys might know that is worth mentioning?

# Answer
A while back I sat down and tried to come up with all of the fundamentally-different MMO combat roles I could, and I ended up with the following list. Note that this is pasted pretty much directly out of my voluminous ideas file and makes a lot of references to WoW, since that's what I was playing when I wrote this up.

**Standard trio**

DPS: Kill monsters through sheer quantity of outgoing damage.

Tank: A tank's sole job is to take a lot of damage (or, rather, to *not* take a lot of damage when anyone else *would* be taking a lot of damage.)

Heal: Repair damage done to tank or to other players.

**Conventional support**

Buff: Make the group more powerful. Difficult to make fun - you'd need a situation where the optimal buffs were constantly changing.

Debuff: Make the enemy monsters less powerful. Again, difficult to make fun.

Crowd control: Completely nullify single enemies or groups of enemies so that the players can focus fire more effectively.

Screening/defense: I'm thinking there's a distinction between "heal damage that has been taken", "be a tank", and "prevent damage to other players". Some kind of a super-discipline priest. Fundamentally different, but difficult to show that.

**Unconventional support**

Sniper: Class whose sole purpose is to nullify single important parts of enemies. "Spell interrupter" would be a form of this. As a slightly more complex example I'm imagining a group of enemies that have a "damage-dealing module" and a "damage-reflecting module", where only one can be disabled at a time - disable "damage-dealing" for the group that the players aren't killing, and "damage-reflecting" for the single creature the players *are* killing. Things can get arbitrarily complex from here.

Threat management: Usually rolled into tank, but why? Make a class that can funnel threat from one character to another, or modify how threat is accumulated, or masquerade as one character. Misdirection+Intervene+Vigilance+more.

Command: Raid leading is tough. Make a "class" whose sole purpose is to direct players, give them a bird's-eye view of the battle, stop forcing them to run their own character as well as the raid.

Mobility/positioning: We've got a little of this with Death Grip, and now Life Grip in Cataclysm, but a class whose sole purpose is to move players or monsters around for optimal placement. Imagine some kind of crazy Thaddius/Hodir combo, where positioning is vital and everyone is moving around constantly, with this dude fixing issues as they come up.

Recon: A class built around dealing with monsters that have not attacked yet - the ability to interrupt/redirect patrols, see who's coming before they come, split up groups temporarily. Rogue has a little of this with Distract.

---

Obviously it's difficult to come up with a way that many of these can actually be, you know, interesting, but I don't think it's impossible. You would, however, need a thoroughly different model from WoW's. Also I kind of dread the idea of "okay it's time to go run Deadmines, we need twelve players from twelve completely different classes", so I feel like any functional game would either just pick a different set/layout of these from WoW or wrap up a bunch of them into one class.

Just as an example of a possible combo, I really like the idea of Tank+Debuff+Sniper being one class, Threat+Mobility being another, and DPS+Healing being the third more common class. Your tank's job is to stay alive and keep the monsters from obliterating the party, you have one utility character constantly trying to redirect every monster to the tank and keep people out of fire, and you have three damage-dealers punching enemies and making health fly out. I think there's potential here. You can easily generate other interesting combos by just mixing and matching various roles.

It's also worth pointing out that, with these roles in mind, WoW's "standard trinity" is actually much more complicated than you might think. It's not just "Tank/Heal/DPS", it's Tank+Threat / Heal / DPS, but virtually everyone is also Buff/Debuff, DPS often has CC, Priests do Screening, and half a dozen classes have Sniper (for spell interrupts). But those are always in a rather minimal form, it's never the focus of the class.
> 13 votes

# Answer
If you step back one level of abstraction all of the various character classes boil down to 3 archetypes. The extremist, the specialist, the Jack-of-All-Trades.

* The Extremists prioritizes one stat/ability to its limit in exchange for weaknesses in all others
* The Specialist prioritizes a small group of stats/abilities (to a lesser degree than the extremist) in exchange for weaknesses in all others.
* The Jack-of-All-Trades has average ability in all stats/abilities.

The more stats/abilities you have in the game the more extremists & specialists you can have.
> 9 votes

# Answer
Worth checking the recent post from Richard Bartle (co-creator of MUD), on the evolution of the DPS/tank/heal team structure, and alternatives.
> 3 votes

# Answer
You might get some ideas from here: http://en.wikipedia.org/wiki/List\_of\_Magic:\_The\_Gathering\_keywords

Magic is so lovingly designed - it's just a shame they obsolete and replace their wonderfully designed series after what feels like five seconds... it's a business model I guess - but it doesn't get my money anymore.

Your archetypes are going to vary wildly based on the context. A grand strategy game might have 'civilian', 'land military', 'naval military', 'air military' concepts, for example.
> 3 votes

# Answer
TVTropes has an interesting list of archetypes in game characters. While the terms used are less than technical, I'm sure you can translate them to whatever vocabulary you wish to use.
> 3 votes

# Answer
I think this would be relevant more in fantasy style RPGs, but stealing from competitive Pokemon battling:

* Special Sweeper/Special Wall - A sweeper being one that is designed primarily for attacking with high speed and special attacking skill, and a wall for blocking opponents with high hp, defenses. Special meaning high magic attack/defense.
* Physical Sweeper/Physical Wall - Same as above, but for physical attacks.
* Healer - Kind of obvious.
* Trapper/Annoyer - The one that would lower stats, restrict, and in some types of games stop mobs from running away.
> 2 votes

# Answer
There's a part about fighting game archetypes in this paper: Fighting genre design guidelines.

And I am currently working on a taxonomy for some of the most famous fighting games (just have had a little time to do it recently).

I think it's important to go away from older loose definitions such as grapplers. A grapple is a mechanic and not truly a gameplay style, a character can be fast and still have special command throws e.g Yang/Yun in Street fighter. I instead use the term Slow/strong for a slow but very strong character, which is a more accurate term for a character like Zangief as there are characters who are strong and slow but do not have any command throws.

The archetypes that exist in the fighting genre are, according to me:

* Slow/strong
* Strong Control
* Control
* Speed Control
* Fast/weak
* Short combo speed
* All around
* Explosive.

(Check my blog or my full research report on mechanics and examples if you are interested.)
> 2 votes

# Answer
leader - helps keep the team fighting and helps them fight better

controller - debuffs the enemies, are damage to keep swarms at bay
> 1 votes

# Answer
Some other types I've seen in games I haven't written on my first post are.

Fighting: Sacrifice (Samurai Showdown Rasestusmaru)- sacrifices something for better performace in the given example it life for a full rage meter.

Tabula Rasa (Darkstalkers Marionette and shadow)- one is a character that copies his enemies while the other possess the previous character beaten.

Card Games: Sacrifice/Recycle decks- discard to get a tactic going and recycle cards for viability.
> 1 votes

---
Tags: game-design
---


# Question
Title: Is there an SDK to write console apps to simulate an Xbox 360 controller?
Is there any SDK I can use to write a console app that can connect to an Xbox 360 as a controller and simulate controller interaction?

# Answer
> 1 votes
I don't exactly have a turnkey answer to your question, but a BeagleBoard would be an ideal piece of hardware to use to simulate input.

It can act as a USB Host or Device and you can program it to appear as any Device.

You could easy capture and replay controller USB traffic to have repeatable input, or go the route of scripting the events yourselves. Unfortunately, I don't know of any existing project to do so.

---
Tags: c#, xbox360, controllers
---


title: Sort Polygons in order - not working?

text:
# Question
Title: Sort Polygons in order - not working?
I'm fairly new to programming in a 3d world.

I'm trying to create a canvas where all the objects are drawn in order of furthest-to-closest and from bottom to top - so they don't overlap each other, but there are problems.

As you can see, some of the objects are overlapping each other. None of the objects in the screen will be moving so I was wondering: is there an algorithm available to sort the objects in the correct order? At the moment I have them sorting in the Z axis ascending, then X descending and Y descending.

# Answer
As @dreta mentioned in the comments, the typical way 3D engines solve this is with a depth buffer and using the hardware depth test, which allows you to draw arbitrarily-shaped objects in any order and will keep track of the closest surface at each pixel. Manually sorting objects is also possible, but will not necessarily handle nonconvex objects or overlapping objects correctly.

However, if you do want to sort objects, you'll need to calculate a depth value for each object, then sort by descending depth. To get the depth, if you're using a typical 3D engine setup, you'll need to transform each object's center point through your view matrix (which goes from world space to view space), then take the negative of the Z coordinate of the result. (Negative because in right-handed coordinates with X and Y aligned with the screen, Z will be pointing out of the screen.)

If it's always an isometric view like this, you can probably get away with calculating depth = ±X ± Y - Z, where the ± means: pick the sign that makes depth increase as you get further away from the camera. That will depend on the orientation of your X and Y axes.
> 3 votes

# Answer
Check out the Painters Algorithm and its disadvantages.
> 1 votes

# Answer
In general, the answer to your question ('is there an algorithm available to sort the objects in the correct order?') in arbitrary 3d settings is *no* \- no such algorithm can exist, even when the objects are as simple as triangles. It's easy to construct three triangles with a cyclic overlap; for instance, imagine looking down the Z axis at three long, thin triangles:

* A: (2.1, 1.9, 1), (1.9, 2.1, 1), (-1, -1, 0)
* B: (-2.1, 1.9, 0), (-1.9, 2.1, 0), (1, -1, 1)
* C: (2.1, 1, 0), (1.9, 1, 0), (-2, 1, 1)

Then where A and B overlap on-screen (near the XY point (0,0)), B will be on top (have the higher Z value): its Z value will be approximately 0.66 whereas A's will be approximately 0.33. Similarly, where A and C overlap (near the XY point (1, 1)), A will be on top; and where B and C overlap (near the XY point (1, -1)), C will be on top. There's no way of ordering these three triangles such that drawing them to screen in the specified order will give the correct result.

As Nathan Reed suggests, the fact that you're in an isometric view means that you would probably be able to avoid this particular issue; the question is whether it's worth avoiding or not, and that's more contingent on your environment and the particular functionality you have available. Most platforms you could be developing on have at least *some* form of 3d rendering readily available, though, and my first inclination would be to just piggyback on top of that for your purposes.
> 0 votes

---
Tags: c#, 3d, isometric
---


title: repeating 2D world

text:
# Question
Title: repeating 2D world
I have a 2D world of 50\*50meters and a viewport of 15\*10meters.

Current situation:

```
if(player.x>World.WORLD_WIDTH){
    player.x = 0;
}
if(player.x<0){
    player.x = World.WORLD_WIDTH;
}
if(player.y>World.WORLD_HEIGHT){
    player.y = 0;
}
if(player.y<0){
    player.y = World.WORLD_HEIGHT;
}

```

So when the player will be placed on the other side of the world when he reaches the border. The camera is always oriented on the player which results in an ugly "jump" when the player is replaced on the other side.

How can i optimize my render-class to flewless render my world.

example:

The player is at location {0,0}. on the right the world should be rendered normal {0,0} - {7.5,0}. And on the left i want to show the other end of the world {-7.5,0} - {0,0}. Same for the Y axis.

I am shure this is a common questen and asked several times here, but i have not found anything with the searchterms "infinite world" or "repeating world".

any advices?

# Answer
These links might help:

http://www.gamedev.net/topic/624243-infinite-procedural-world/

http://www.gamedev.net/topic/599544-isometric-world-wrap/
> 0 votes

---
Tags: 2d
---


# Question
Title: Mouse click rectangle doesn't update to actual mouse position
I'm making a menu in XNA; and to solve clunky input via arrow keys, I thought I would use mouse input. I got everything to work perfectly, then I tried to click on something specific and nothing happened. To troubleshoot, I drew an image where the cursor rectangle is supposed to be. As you can see in the image below it's nowhere near my mouse.

One image of the cursors lag

Another image of the cursors lag

Note how they are in two different places.

How do I fix this horrible lag?

The menu update calls a mouse class to update the mouse position and place it within bounds of the screen. The mouse class also has a rectangle that updates based on the mouse position, but it updates almost 200 pixels away. The mouse moves fine in game, it's just the rectangle is in a weird position

```
   //This is located in the Mouse Class
    public void Update(GameTime gameTime)
    {
        oldmouse = currentmouse;
        currentmouse = Mouse.GetState();
        Position.X = currentmouse.X;
        Position.Y = currentmouse.Y;
        //Some other boundary code that's not essential
        clickRectangle.X = (int)Position.X;
        clickRectangle.Y = (int)Position.Y;
    }

    // this is located in the menu class

    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(ArrowTexture, mouseInput.clickRectangle, Color.White);
        //draw other arrows and text
    }

```

I don't see a problem with the code. Is there something else I have to do?

I should also mention it sometimes draw nearer to the actual cursor and sometimes farther away. The cursor only drew to my actual cursor once before it stopped working.

EDIT: I updated the question with more relevant information. I apologize for not including it earlier.

# Answer
> 3 votes
Welp, long after I figured out the problem.

Early in my menu development I inherited the "Game" class from XNA. I forget why, I think it had to do with getting certain method to work or something. I guess I had removed the code that need the inheritance and kept the inheritance which screwed up my update method. It wanted to override it but I didn't do that. Anyway I removed the inheritance and it worked fine.

Doi.

---
Tags: xna, c#, mouse
---


# Question
Title: Unity3D - different object with the same mesh imported from Blender
I would like to instantiate different objects (i.e. poker chips with different values) that actually share the same mesh imported from blender. To this end I have copied the assets and changed the texture but all the assets automatically switch to the last texture I choose as they are actually the same entity. What am i doing wrong?

# Answer
> 2 votes
You need to create different materials with different textures. To apply this new material just drag and drop it the the empty space in Inspector view. You will see the material change and corresponding texture will be applied. Now you can change texture associated with this material and all the mesh which use this material will have same texture.

---
Tags: unity, blender
---


# Question
Title: C# multi-player socket server (need clarification/suggestions)
I've been working on an 2D-RPG for a while and I recently decided to make it into an MMO (not really massive, but multi-player). Anyways, I'm attempting to write a game server in C#. Yes, I know I could use a commercial solution like SmartFoxServer or Photon, but I want to make it a learning curve by going through the pain of doing it myself. It's pretty much going to be a simple zone-room architecture that handles events and sends position updates a few times in a second.

A lot of articles I read recommended using UDP but I'm limited to TCP because my client will be a browser based flash file. I've pretty much worked out in my head how I want everything to work, the binary protocol and etc, but I'm stuck at the beginning.

I'm not quite sure how to start. I've read about 3 different types of socket communication in C#:

1. **Blocking** \- I know I can't use this because the main thread will be blocked when accepting connections and etc.
2. **Non-Blocking**
3. **Asynchronous**

I don't know which is the better, or the obvious choice for what I'm trying to do. I want the server to be scalable and handle a few hundred concurrent connections. I tried to study SFS and it seemed like it had multiple thread pools, for accepting connections, receiving data and sending data respectively. I had it in my mind that I would do it the same way and use the ThreadPool class, but I'm not sure of the difference between non-blocking and asynchronous.

Can someone clarify to me the difference between the two and which one is the better choice for me. I would appreciate any link you think might help as well.

# Answer
Non-blocking is basically the same thing as asynchronous: if you use the async features of .Net sockets you will get non-blocking code for free.

I doubt you are using C# 4.5 so you will need to resort to the 'older' way of doing non-blocking IO. The following is a snippet which deals with how to stream data from a TCP connection (you will likely want to use UDP, but the core principles are the same):

```
private Socket _socket;
private ArraySegment<byte> _buffer;
public void StartReceive()
{
    ReceiveAsyncLoop(null);
}

// Note that this method is not guaranteed (in fact
// unlikely) to remain on a single thread across
// async invocations.
private void ReceiveAsyncLoop(IAsyncResult result)
{
    try
    {
        if (result != null)
        {
            int numberOfBytesRead = _socket.EndReceive(result);
            if(numberOfBytesRead == 0)
            {
                OnDisconnected(null); // 'null' being the exception. The client disconnected normally in this case.
                return;
            }

            var newSegment = new ArraySegment<byte>(_buffer.Array, _buffer.Offset, numberOfBytesRead);
            OnDataReceived(newSegment);
        }
        _socket.BeginReceive(_buffer.Array, _buffer.Offset, _buffer.Count, SocketFlags.None, ReceiveAsyncLoop, null);
    }
    catch (Exception ex)
    {
        // Socket error handling here.
    }
}

```

Also remember that dealing with 100's of users (as opposed to 1000's) is actually pretty easy. If you keep your networking code and your game code on different threads you ***might*** even be able to get away with blocking sockets (non-blocking/async was involved in solving the C10K problem).

I have a blog post on the matter which you might find useful.
> 1 votes

---
Tags: c#, multiplayer, client-server, multithreading, socket
---


# Question
Title: How should I structure my Tetris clone's code?
I programmed my first game (a Tetris clone in XNA) and all my code is in a `Game1.cs` file with 730+ SLOC. It's fairly well-commented, and each piece of functionality has its own subroutine, but I have a feeling that I'll have to move toward a more organized approach as my games increase in complexity.

To offer some background, my current approach separates the "view" (the tetrimino sprites visible on the board) from the underlying "data" (represented by an 18x10 bool array), which determines if there is a block at some point on the grid. In other words, my "data" determines my "view." Also, here's a list of all my subroutines:

```
Game1()
Initialize()
LoadContent()
UnloadContent()
GetBlockType()
IsFreeBlock()
IsPossibleMovement()
GetXInBlocks()
GetYInBlocks()
StorePiece()
DeleteLine()
DeletePossibleLines()
IsGameOver()
ResetBoard()
Update()
Draw()

```

I hear a lot about game components in XNA, which sounds like something that could make my code more organized and extensible. Are there any organizing features of XNA that I could incorporate into my future games?

# Answer
> 4 votes
I like the component architecture, but for a Tetris-clone it might be overkill. Instead I would just move away from the monolithic Game-class to separate classes. Here's an idea how you could separate into several classes and what methods/properties they could have:

```
Board
  - reset()
  - checkCollision(Tetromino)
  - canRotate(Tetromino)
  - commit(Tetromino)

Tetromino
  - get/set position
  - rotate()

GameController
  - spawnBrick()
  - processUserInput()
  - increaseSpeed()
  - updateBoard()

Renderer
  - RenderBoard(Board)

```

You could also use messaging or events to attach other subsystems. Eg. your Board could send a message when a row was cleared. Then a "SoundController" could listen to this message and play a sound, or your "ScoreManager" could update the score. etc.

---
Tags: xna
---


# Question
Title: Problem using ccTouchesEnded/ccTouchesBegan to move sprite in cocos2d-x?
I'm using ccTouchesBegan/ccTouchesEnded to move sprite from one point to another but I'm having problem, if i give two or more consecutive inputs one by one while sprite is moving(runAction is being performed). It first moves to last point i touched and then teleports itself to previous touched points one by one.

# Answer
> 1 votes
To detect mulitouch use ccTouchesBegan as described in tutorial at cocos2d-x site. To detect single-touch you can use ccTouchBegan as described here.

# Answer
> 1 votes
It does it because you are running two actions at the same time. Before making the sprite take an action just make it stop current/all actions he's doing.

---
Tags: c++, cocos2d, cocos2d-x
---


# Question
Title: Most effective way to manage a gamestate system that is easy to use?
I just started working on my game, mostly the game management. I plan and using game-states to make the menu's and other stuff easier.

My main idea for implementing the game-states is creating a game object and passing it as a reference to classes which control the current state, then storing the game-state classes via references inside a vector.
My main concern is that is this the better way to do it? Or should I implement it differently? Also, when you do use game states, where does the game loop go? Does it go inside a state such as *gamePlaying* or is it put somewhere else?

Hopefully someone can clear this up for me, thank you!

# Answer
> 9 votes
I usually implement a state-machine similar to this:

```
StateMachine
   + changeState(State)
   + getCurrentState()
   + update()

State
   + enter(StateMachine)
   + update(StateMachine)
   + exit()

```

When a state becomes the active state, the `StateMachine` calls the `enter` method. The `StateMachine` continiously calls `update` on the active state. When the state changes, `exit` will be called on the currently active state. The `StateMachine` passes itself as parameter to the `enter` and `update` methods, so that the State can initiate a state-change by itself.

Here's a pseudo-code example.

**StateMachine:**

```
// example for the StateMachine
Game implements StateMachine
{
    void changeState(State newState){
        if(currentState){
            currentState.exit();
        }

        currentState = newState;

        if(currentState){
            currentState.enter(this);
        }
    }

    State getCurrentState(){
        return currentState;
    }

    void update(){
        if(currentState){
            currentState.update(this);
        }
    }
}

```

**Example State:**

```
// example for a state implementation
IntroState implements State
{
    void enter(StateMachine sm){
        // start the intro
    }

    void update(StateMachine sm){
        if(introComplete){
            // change the state!
            sm.changeState(new GameState());
        } else {
            // play the intro
        }
    }

    void exit(){
        // nothing to do.. maybe free some stuff?
    }
}

```

**Main:**

```
// the main method that starts everything up..
main(){
    Game game = new Game();
    game.changeState(new IntroState());
    while(runGame){
        game.update();
    }
}

```

This architecture doesn't need `switch` or lengthy `if` statements. It's also really easy to change the flow of the states or add in new states. Imagine you wanted to start the `MainMenuState` after the `IntroState`? Change one line to: `sm.changeState(new MainMenuState());`. Then in the `MenuState` you could branch into whatever `State` you want, depending on which buttons have been pressed etc.

# Answer
> 3 votes
The most important thing you can do right now is actually just to make your own implementation without much regard to whether it's the "right" solution. Just write some code. You'll quickly find where the pain points are.

Having said that, one solution that works well for me is to have a Screen base class and a ScreenManager class. The ScreenManager class manages a list of Screen instances in a vector, calling Update and Draw on each one every game loop. One instance of the ScreenManager class is created at initialisation time in the main class (note I didn't say singleton. Generally you don't need singletons) and its Update and Draw methods are called from there at the right times. ScreenManager has methods AddScreen and RemoveScreen. Each inherited Screen class has access to the ScreenManager through a member of the base class (this value is set in ScreenManager.AddScreen) so each screen can remove itself and add new screens.

In this way, your game states are actually just screens, so you'll typically have a main menu screen, an options screen, and a game play screen etc, each with their own Update and Draw methods.

# Answer
> 0 votes
You could have a pure virtual class called game state. Then inherit from this class whenever you make a different game state, such as main menu or in game. You would have an `enum` that would be for your game states. You would also need one that was for not making a change. If you need to change the game state the current state will request the change. Then in your main game loop you would have a place to check if you need to change.

You can then utilize `new` and `delete` to facilitate the change in states. For instance, when you first start the game, you would have something like this pseudo code:

```
currentgamestate = NO_CHANGE;

gamestate = new IntroState;

while(shouldplay)
{
     gamestate->HandleEvents();
     gamestate->HandleLogic();
     gamestate->HandleRendering();

     if(currentgamestate != NO_CHANGE)
     {
           delete gamestate;
           switch(currentgamestate)
           {
                case INTRO:
                {
                      gamestate = new IntroState;
                      currentgamestate = NO_CHANGE;
                      break;
                }
                case MAIN_MENU:
                {
                      gamestate = new MainMenuState;
                      currentgamestate = NO_CHANGE;
                      break;
                }
           //and continue for each state and make this portion a separate function

```

This way you only have to deal with one switch statement for your states and your main game loop only deals with the one game state instance. You just have to insure that your constructors will create the bits they need to create and the deconstructors do their job right. Content loading and what not will happen automatically when you create the new state if you put it in the constructors. You can also have engine tools such as a renderer or a collision detection tool pass a reference or pointer of themselves into the different functions so you game states can utilize that code in their functions if they need to.

You could even have just gamestate-Run(); and run the three portions of events, logic, and rendering, inside the different gamestate classes. Up to you really.

# Answer
> -3 votes
I'd suggest making your main game class a singleton and using `public` functions to change the state.

I'd implement the game loop within the singleton game class and have a `switch()` statement with `case`s for your various game states that call functions for whatever actions you want to do within each state.

---
Tags: c++, vector, sdl, game-loop
---


title: Infinite time of rotation

text:
# Question
Title: Infinite time of rotation
I want the rotation of the sprite. So that I used RotationModifier, but in that I have to specify the time interval you want the rotation. But I want to create rotation which was infinite. So please help me.

# Answer
> 5 votes
LoopEntityModifier is the way to go!

Not sure, but it may end as something like this:

```
LoopEntityModifier EntityModifier =
                   new LoopEntityModifier( new RotationModifier(yourargs) );

```

# Answer
> 5 votes
What about (pseudo-code):

```
update(float dt){
    sprite.rotation += degreesPerSecond * dt;
}

```

---
Tags: andengine
---


# Question
Title: Is it possible in HLSL to use bitfields?
I have in memory a representation of my 2d GameMap (think of a Scorched Earth like landscape).

The map is made up of MapElements, a MapElement is made up of 64 bits defined like

```
struct MapElement {
 uint Color;  // RGBA Color
 uint Info;   // info flags (collision, material etc)
}

MapElement Map[Height * Width];

```

Now I'm thinking of doing some effects in HLSL, for example lighting, that need per-pixel collision information. Is there any way I can just upload the mapdata as I have it in memory, and use it in HLSL ?

So is there a way to in HLSL to sample Uploaded Map to see if (map\[y\*Height+Width\] & CollisionFlag) != 0 ?

# Answer
> 1 votes
You could try creating a Texture2D (or Texture1D) with `DXGI_FORMAT_R32G32_UINT`, or a generic Buffer and updating that with data from your map array when changes occur.

Then you should be able to do `uint2 mapElement = texture.Load(...)` or `uint2 mapElement = buffer.Load(y*Height+Width);`

`Load(...)` might work better for you than the regular `Sample(...)`, since it will not perform any sort of filtering or interpolation, and allows you to access the elements by index/offset rather than UV coordinates.

# Answer
> 1 votes
Storing this type of data in a texture is pretty common, and not that difficult.

I'd keep a couple of things in mind:

Your texture sampler (which is used to read data from the texture) **is going to return floats, not ints**. This has the potential to introduce some precision issues.

For instance, in my raycaster, I'm storing an octree in a texture, using a single texel per tree node. Each texel has the format:

```
   a = 0.2 == inner node
   r - texel x of first child
   g - texel y of first child
   b - reserved

   a = 0.5 == leaf node
   rgb == color

   a = 0.9 == empty node
   rgb = reserved

```

When checking the node type in the shader, I read the texel value from the sampler, then check the node type by *range*, not via an exact match.

```
if (a <= 0.3) node_type = INNER
else if (a <= 6) node_type = LEAF
else node_type = EMPTY;

```

Since 0.3 might be read as, for example, 0.299999, just checking if it's equal to the flag value of 0.3 isn't guaranteed to work, so I spaced the flag values (inner, leaf, empty) far enough apart to allow me to check a range without worrying about precision errors.

**When you're calculating the address of the texel** where your flags and color are stored, you're using

```
if ((map[y*width+x] & CollisionFlag) != 0)...

```

Since youre texel coordinates are normalized (0.0--0.999), you'll need to do this a bit differently:

```
texelX = (pixelX+0.3)/width;
texelY = (pixelY+0.3)/height;

```

... where pixelX and pixelY are the familiar int coordinates, and texelX/texelY are the normalized values you'll use when sampling in the shader.

The `0.3` offset is so that you read the texture from the middle of a texel, not from the edge which produces different behavior on different hardware. We use 0.3 instead of, say, 0.5, so that this doesn't accidentally round up to the next coordinate.

There are a lot of good explanations on this process available on AppHub and elsewhere if it's not clear.

**HLSL, as of SM 3, doesn't support bitwise operators in shaders**. You can perform a shift via normal arithemetic operations such as,

```
// check bit 3 (0-based, fourth bit)
if ((flags / 8.0)  > 0 && (flags / 8.0) < 1.5) /// bit is set

// check bit 5
if ((flags / 32.0) > 0 && (flags/32.0 < 1.5)) /// bit is set

```

However, you may have to perform some magic here since the bits in the float you read from the texture don't necessarily match what you put in the `int` to start with. You might be better off using `float` ranges similar to what I described above, and using each of the RGB components separately.

Good luck!

---
Tags: xna, textures, hlsl
---


# Question
Title: When is it the right time to start teaching collision detection?
I and a friend of mine started a game development club in our school two months ago and everything is going well for now. We are following McKesson's tutorials which I find comprehensive and well-built.

We have come to the point where we started making simple prototypes of easy-to-do games, like 3D Pong (not as polished as the referenced version), and soon we are going to finish the second part of the tutorials (the Positioning of objects). We have ideas for prototypes which involve little more complex collision detection and I started wondering is it a good place to look in depth at this topic of game programming? And should I also include the BSP, quadtrees, octrees and other partitioning algorithms with it?

# Answer
As I said in the comments.

The "right time" is when you want to make a game that needs that feature.
> 5 votes

---
Tags: c++, opengl, collision-detection
---


# Question
Title: What are "view frustum", "focal length" and near plane distance?
I've been reading through "Mathematics for 3D game programming and Computer Graphics" lately. Specifically definition of the view frustum and how the APIs generally process it, author introduces the concept of a length `e` which he classifies as the focal length. And it makes absolutely no sense, isn't the whole notion of focal length incompatible with the pinhole camera concept (inf. small) which is at the heart of 3D APIs as Direct3D and OpenGL? I thought all I need is the aspect ratio, the distance from the near plane and the FoV which can be established from the distance from the near plane.

And then he simply drops it and speaks of near plane distance `n`, which I thought was the actual value of `e`. What gives? Isn't the distance from the near plane the same as the "focal length" since we're talking about a pinhole camera? How do they differentiate?

# Answer
The focal length *controls* the field of view. That is, they're mathematical transforms of each other: changing one changes the other. The longer the focal length, the smaller your field of view.

So your FOV parameter is merely a re-stated form of the focal length.

The "common projection matrix" doesn't really use a focal length. The actual focal length is always the same. These matrices implement FOV as a scale applied to the X and Y camera-space coordinates. This is just to make the math easier; being able to keep the eye point at a fixed location makes the math simpler. But in terms of the results, either produces the same results.

> Isn't the distance from the near plane the same as the "focal length" since we're talking about a pinhole camera?

No. The near plane is *irrelevant*; the near/far planes exist *solely* for near/far culling of rasterized triangles. They're important mathematically for computing the depth value (which ties into depth buffers), but they have no effect on the visuals of the scene (outside of depth buffer artifacts from having a close near plane).
> 6 votes

---
Tags: 3d, terminology, frustum
---


title: C# XNA Elasticity Behavior

text:
# Question
Title: C# XNA Elasticity Behavior
What is elasticity? How do I implement such a thing?

# Answer
> 11 votes
Elasticity can be defined in two ways; either to do with physics or to do with how you move from one value to another (tweening).

# Tweening

This is used in games to move between two values - for example you might have a set of points that the game camera needs to move between over time. The simplest tween is a lerp (also known as a linear tween):

```
Lerp(float initial, float target, float amount) =>
    initial + (amount * (target - initial))

Linear(float initial, float change, float amount) =>
    initial + (amount * change)

```

In order to use this function you must provide it with an initial value (for example, the camera starting position), the change required to get it to the target (where you want it to move to) and how far along that line you want it to be (a value between 0 and 1 - e.g. 0.5 would be half way to the target). The result of a lerp looks like this:

An elastic tween makes the value 'bounce' at the start, the end or both (ease in, ease out and ease in out respectively).

*Ease in elastic:*

*Ease out elastic:*

*Ease in out elastic:*

The MCTween animation types page will let you see these as animated graphs/values.

Mono Game Extended (the successor to XNA) has a Tweening Package available through NuGet.

# Springs

An elastic band in physics is usually represented by a long chain of very short interconnected springs, that are connected using a revolute joint (you may limit the angle) and that have a very high dampening factor. This means that each spring:

* Isn't likely to bounce back and forth
* Can revolve around the connection to the next spring

The whole system behaves as follows:

* It can be used like a rope - e.g. it is flexible (due to the revolute joints)
* It will snap back to its original length if stretched

Velcro Physics (Formerly Farseer Physics) has springs.

# Elastic and Inelastic Collisions

An elastic collision is when the kinetic (movement or momentum) energy of colliding bodies remains the same after a collision (it can still be distributed differently between the bodies). This means that no energy is lost to other forms of energy (for example, sound, heat and light). Elastic collisions (or "super-elastic", where the energy is greater) only happen at the molecular level - however elastic collisions can be passable in games.

An inelastic collision is when a portion of the kinetic energy is converted to other forms of energy. For example, when two billiard balls collide you hear a sound (although this does have a negligible impact on the total momentum). If a car collides with another one a lot of energy is lost to deformation and heat. At the macro-scale these types of collisions are more accurate; and will generally improve the stability of your physics simulation (they reduce the chance of a rounding error or such from introducing more energy).

Wikipedia has very good articles on both elastic and inelastic collisions, Physics for Game Programmers has a free excerpt on both.

# Answer
> 9 votes
Checkout Robbert Penner's easing classes and examples. They are very easy to convert to C#.

# Answer
> 5 votes
I don't know what you mean exactly by "elasticity". If you mean **rope simulation** or **grid/cloth simulation**, here is how to proceed :

A rope/string is simply a list of points connected together with springs :

Force applied on a point depends of forces received from the two neighbours springs :

Force applied by a spring on a point is calculated like this :

```
F = springvector / length * (length - normal_length) * k

```

where :

> springvector = (position of neighbour point) - (position of point)
>
> length = actual length of spring
>
> normal\_length = default length of spring when no force is applied on it (constant)
>
> k = spring stiffness (constant)

Now, some code :

```
//init points (only once)
for(int i = 0 ; i < 10 ; i++)
{
    points[i].x = 0
    points[i].y = i; //vertical rope
}

//each frame
for(int i = 0 ; i < 10 ; i++)
{
    vec2 forcePrev = points[i - 1] - points[i];
    float lengthPrev = length(forcePrev);

    vec2 forceNext = points[i + 1] - points[i];
    float lengthNext = length(forceNext);

    vec2 totalforce = forcePrev / lengthPrev * (lengthPrev - normal_length)
                    + forceNext / lengthNext * (lengthNext - normal_length);

    velocity[i] = velocity[i] * 0.98 + totalforce * 0.001;
    velocity[i].y += gravity;

    tmp_points[i] = points[i] + velocity[i];
}
copy all points from tmp_points to points

```

You can also skip simulation of some points and explicity set their position if you want them to be fixed (usually first point of rope is like this).

If you want to do **grid/cloth simulation**, this is exactly the same thing, but instead points are arranged as a grid, and forces are received from more neighbour springs :

Here is some pseudo-code :

```
foreach(point in grid1)
{
   vec2 totalforce = new vec2(0, 0);
   foreach(neighbourpoint in point.neighbours)
   {
      compute force from neighbourpoint to point
      add force to totalforce
   }
   apply totalforce to point, store it in grid2
}
copy all points from grid2 to grid1

```

# Answer
> 4 votes
You can check XNA Tweener library that has *Elastic* function among others. Its an adoption of Robbert Penner's easing framework.

---
Tags: xna, c#
---