# Question
Title: Unity 2d: How stop movement when object hit a wall
I created a square that slides on a flat ground.

```
public class PlayerMoveScript : MonoBehaviour
{

float move = 0;

    void Start (){}

    void FixedUpdate ()
    {
        if (move == 0) {
            move = Input.GetAxis ("Horizontal");
            if (move != 0) {
                move = 15*Mathf.Sign(move);
                rigidbody2D.velocity += new Vector2 (move, rigidbody2D.velocity.y);
            }
        } else
            {
            rigidbody2D.velocity = new Vector2 (move, rigidbody2D.velocity.y);
            }

    }
}

```

On both sides of the ground lies a wall, when the square hits a wall and stops his movement, the square instead continues to push in his direction. What I trying to do, is that when the square hits the wall, the square stop the movement and stop to push on the wall, in a way that the player can choose a new direction until the square will hit a new wall.

So imagine a big picture frame, a little square lies on the center.

1. The player hit the down key
2. The square starts to move down, with a constant velocity
3. The square hits the bottom side of the frame, and it stops
4. The player choose a new direction.
5. The square starts to move in the new direction
6. Back to 2

N.B: The walls are rigid bodies 2d with a box collider 2d.

# Answer
I would keep track of the current direction and reset it every time the box collides with a wall, like so:

```
public float speed;

private Vector3 currentDirection = Vector3.zero;

void Update()
{
    if (currentDirection.Equals(Vector3.zero))
    {
        Vector3 inputDirection = new Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"), 0);
        if (!inputDirection.Equals(Vector3.zero))
        {
            currentDirection = inputDirection;
            this.rigidbody2D.velocity = currentDirection * speed;
        }
    }
}

void OnCollisionEnter2D(Collision2D col)
{
    currentDirection = Vector3.zero;
    this.rigidbody2D.velocity = Vector3.zero;
}

```
> 4 votes

# Answer
Based on how you explained your movement one simple way of doing it is...

Raycast in the direction you move there are only four directions so everytime you move

1. Raycast in the direction you are moving.
2. In your update once the raycast gets within a certain distance say 0.2 unity units..
3. dont allow movement in that direction
4. and so once the player pushes a button in that direction you raycast to see if there a wall

For this setup to work you just will need 8 raycasts two for each direction you can move to define the width of the object.

The benefit of doing it this way is that you can keep a certain distance away from your box in otherwords you can define at what distance you want to stop before a collision actually happens which is what you probably want.

Also make sure to raycast only when you are moving.
> 3 votes

---
Tags: c#, 2d, unity
---


# Question
Title: How can I read from multiple textures in an OpenGL ES 2 shader?
How can I enable more than one texture in OpenGL ES 2 so that I can sample from all of them in my shader? For example, I'm trying to read from two different textures in my shader for the player's car.

This is how I'm currently dealing with the texture for my car:

```
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, this->texture2DObj);
glUniform1i(1, 0);
glBindBuffer(GL_ARRAY_BUFFER, this->vertexBuffer);
glEnableVertexAttribArray(0);

int offset = 0;
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, this->vertexBufferSize,(const void *)offset);

offset += 3 * sizeof(GLfloat);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, this->vertexBufferSize, (const void*)offset);

glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->indexBuffer);
glDrawElements(GL_TRIANGLES, this->indexBufferSize, GL_UNSIGNED_SHORT, 0);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);

```

# Answer
> 4 votes
In brief, you want code like this:

```
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, this->texture2DObj);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, this->otherTexture2DObj);
GLint samplerArrayLoc = glGetUniformLocation(shaderObject, "texture");
const GLint samplers[2] = {0,1}; // we've bound our textures in textures 0 and 1.
glUniform1iv( samplerArrayLoc, 2, samplers );

```

You bind your textures into two different texture slots (in this case, GL\_TEXTURE0 and GL\_TEXTURE1), then set your shader uniforms to tell the shader which texture slots to use for their texture lookups.

In this code, I assume that your shader will receive these samplers as `uniform sampler2D texture[2];` You may alternately have them as separate uniform variables rather than a single uniform array, in which case you'd set their values separately, instead of in a single call.

Then your shader can just read from either `texture[0]` or `texture[1]` to sample from either of the two textures.

And that's pretty much all there is to it!

# Answer
> 1 votes
You need to fist query the sampler uniform locations with glGetUniformLocation, then set the sampler to the same texture unit that you've enabled with glActiveTexture. Thus, some sample code for this would look like:

```
mySamplerLoc = glGetUniformLocation(programId, "mySampler");
...
glUniform1i(mySamplerLoc, 0);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textureId);

```

And repeat that for as may textures as you like, replacing the 0 and GL\_TEXTURE0 by the corresponding texture unit you wish to bing the texture to.

And of cource, make sure you add the uniform variable declarations in the shader:

```
uniform sampler2D mySampler;
void main()
{
    vec4 color = texture(mySampler, texCoords);
    ...
}

```

Noting that you should avoid querying the shader uniform locations every time. Ideally, query them once with glGetUniformLocation() and store the result for further use.

---
Tags: opengl-es2, multitexturing
---


title: Blinn, Normal maps & Fresnel?

text:
# Question
Title: Blinn, Normal maps & Fresnel?
So something came up today when I was going over my Blinn shader. As I've been taught, the half-angle vector is calculated in the fragment shader, and is equal to `normalize(lightDir + viewDir)`. This seems to work fine.

When adding a normal map, this still *seems* to works, except I use tangent space vectors and `dot` the half-angle with the normal from the normal map.

But here's what I don't understand: when using normal maps, shouldn't the light & view directions be re-computed for each fragment? Seeing as the interpolation between the vectors is no longer linear, `lightDir` and `viewDir` can't possibly be correct anymore?

Somehow I feel like the per-pixel normal should play a part in calculating the view/light directions. Am I missing something?

This came up when working on a fresnel effect which also uses the half-angle vector. Without any changes to the half-angle vector, the fresnel effect can't possibly know anything about the normal map, which seems wrong (and actually looks wrong).

Here's the fresnel calculation:

```
 // Fresnel (Schlick approximation)
 float base = 1 - dot(viewDir, halfAngle);
 float exp = pow(base, 5);
 float fresnel = exp + fZero * (1.0 - exp);

```

Given that neither viewDir nor halfAngle incorporate the normals from the normal map, the fresnel effect is computed based on interpolated normals and looks "blocky". Maybe this isn't a problem for the Blinn computation, but I thought it might be too.

# Answer
If you are computing the half-vector in the Vertex Shader and passing it to the Fragment Shader as an interpolated output, there is no guarantee that the normalized vector will remain unit length after being interpolated thru the triangle. So you should at least re-normalize it in the Fragment Shader.
> 2 votes

---
Tags: shaders, glsl, normal-mapping
---


# Question
Title: How to make character gain acceleration?
I want to create more realistic physics for my 2D games.

Currently, the character and the other game objects in my games start moving instantly (achieve maximum speed instantly) and stop instantly (achieve 0 speed instantly).

There is no transition between speed levels - resting and moving, moving and resting.

I heard about 'steering behaviors', but am pretty sure they're mostly for designing AI agents' movements.

**Should I learn steering behaviors to make more realistic character movements in general? (In the physics-aspect). Is this the way to go?**

*If the answer is 'yes', could you recommend a good source to learn them?*

# Answer
> 5 votes
What you are asking about is called acceleration. Easing out and easing in. It is achieved by computing the elements current speed before you move it. The simplest way to do that if your goal is only smoothness in motion is to use acceleration.

You do this like this (pseudo code):

```
p.x = 10.0; // Current character position.
v.x = 0;
maxV.x = 1.0; // Inset different number here.
acc.x = 1.0;  // Insert different number if you like.

if (character_is_moving_in_one_direction_along_x-axis)
  {
    v.x += acc.x;
    if (v.x > maxV.x) v.x = maxV.x;
    if (v.x < -maxV.x) v.x = -maxV.x;
  }
p.x += v.x;

```

---
Tags: physics, movement
---


# Question
Title: Compute world position by walking N units along spline?
My goal is to move ahead along a spline 'x' world units, unfortunately there is no way to map spline points to world points.

What I do is I iterate along the spline by a small alpha amount (say 0.001), get the new spline point vs the old one and add the difference to a total up until it equals or is slightly greater than the distance I wanted to move in world space.

This works fine but there is a huge bottleneck with the sqrt, basically to calculate the distance between two vector points you need to do a square root calculation.

I feel it should be possible to just get the squared value and just use that, unfortunately I can't get the code working, here is what I have:

Where `_distance` is the amount to move, Distance is the alpha value along the spline.

```
        float distanceMoved = 0;

        float oldDistance = Distance;

        while (distanceMoved < (_distance))
        {
            Vector3 before = Position;
            float oldAlpha = Alpha;
            float oldDist = Distance;
            Distance += _iteration;

            distanceMoved += (before - Position).magnitude;
        }

```

Notice the line with `(before - Position).magnitude`, the .magnitude property performs a square root.

I've tried changing it to .sqarMagnitude and say distanceMoved \< distance * distance but it has accelerated the rate of movement forwards.

Any ideas what is going wrong or how I can get rid of the square rooting or do this differently entirely?

# Answer
You shouldn't do a linear search!!! You should opt for a binary search in the first place. Secondly, you should have multiplied the desired distance by itself i.e. `desired_distance_to_move * desired_distance_to_move` than do a binary or (in case you care not of performance) a linear search for a point with a distance * distance \> desired\_distance^2 (and \< \[desired\_distance^2 + 1\]) if you are doing binary search).

How to do binary search in a situation like this:

`a` is the estimated step size.

`t` is the current position on the spline.

`distance_2()` is a function that returns the square distance without using root obviously

`spline()` gets you a position on the spline

```
old_pos = spline(t);
curr_dist_2 = distance_2(old_pos, spline(t + a));
step_size = a;

while (curr_dist_2 < desired_dist_2)
  {
    a += step_size;
    step_size *= 2;
    curr_dist_2 = distance_2(old_pos, spline(t + a));
  }

while (curr_dist_2 > desired_dist_2 + 1 || curr_dist_2 < desired_dist_2)
 {
   step_size /= 2;
   if (curr_dist_2 > desired_dist_2 + 1)
     {
       a -= step_size;
     }
   else
     {
       a += step_size;
     }
   curr_dist_2 = distance_2(old_pos, spline(t + a));
 }

```
> 1 votes

# Answer
If the curvature of your spline is small enough, there is a method that will speed up things while remaining accurate. The idea is the same as developed in my answer to this question: if iterating by `alpha` makes you advance by `distance`, then iterating by `K * alpha` will make you advance by *approximately* `K * distance` as long as `K` is not too large.

Given your desired distance `_distance`, the function becomes as ridiculously short as this:

```
    float const d = 0.001;

    Vector3 oldPosition = Position;

    Distance += d;
    Distance += d * (_distance / (oldPosition - Position).magnitude - 1.0);

```

Now of course if `_distance` becomes too large, the approximation no longer works well. You can fix this by doing a small, reasonable number of iterations instead:

```
    for (int i = 0; i < 10; i++)
        Advance(_distance / 10.0);

```
> 1 votes

---
Tags: c#, unity, optimization, splines
---


# Question
Title: How can I test if a point is behind a polygon in 2D?
In order to improve the performance of my visibility graph generator I am trying to figure out the following.

Given the image below; is there a way to find out if a point is 'behind' the polygon? For example, from the blue points perspective green and pink would be behind the polygon so there is no need to do expensive visibility checks. Is there an easy way to figure this out?

Basically, what I need to know is, when drawing a line from Blue to Green, does it start in or outside the polygon? There must be some simple math for this.

So green and pink are 'behind' and purple and red are in front.

# Answer
> 1 votes
You can create an algorithm based of edge intersection.

The idea is to draw a line between the two points called a ray. This then acts as a line to test whether the polygons lines intersect.

You can do this in pseudo-code:

```
// Method in point:
bool IsPointBehindPolygon( testPoint, polygon)
{
    originPoint = this;
    ray = new Line(originPoint, testPoint);
    foreach(line in polygon.lines)
    {
        if ( LinesIntersect(line, ray) )
        {
            return true;
        }
    }
    return false;
}

```

You can then use this to find if it is "visible" according to a selected polygon and point:

```
void PolyFun()
{
    bool greenCheck = Blue.IsPointBehindPolygon(Green, polygon);
    bool redCheck = Blue.IsPointBehindPolygon(Red, polygon);

    Console.WriteLine( greenCheck ?
        "Blue says: Green is behind the shape" :
        "Blue says: Green is not behind the shape" );

    Console.WriteLine(redCheck ?
        "Blue says: Red is behind the shape" :
        "Blue says: Red is not behind the shape" );

        // Output:
        //     "Blue says: Green is behind the shape
        //     "Blue says: Red is not behind the shape
}

```

Hope this helps.

# Answer
> 0 votes
I would not call this a that simple but here is now you can do it: Let's first have some notations (given the picture you provided):

> A = green dot; B = pink; C = Purple; D = Red
>
> Q = blue;
>
> P = the polygon defined by a set of segments or lines.

So basically you want to know if any line `QA` , `QB` , `QC` , or `QD` intersects your polygon `P` The naive way to do this is to define the polygon with a a set of segments you can use line-line intersection to test this:

```
bool intersect(Polygon P, Line l)
{
   for_each(Line pl in P.segments)
        if(intersects(pl,l)) //line-line intersection
             return true;//line intersects polygon
   return false;
}

if(intersect(P,QA)) -> point A is in front of the polygon relative to Q

```

To simplify the problem i think you want to check if any point `A`,`B`,`C` is visible from the players's perspective `D` and in this case you don't have to take a reference point `Q` you can just do `intersect(P,AD)`, 'BD' and `CD`.

You would basically have to do this for each polygon in your scene which is not that efficient in the end (if you have a big scene). The best approach is to use spacial partitioning like a BSP tree (best for your case) but this is not that trivial to implement.

If you scene is small or relatively small you can use the approach described above and you can even improve this by adding a 2d Grid to store references to polygons that you want to test.

---
Tags: 2d, path-finding, geometry, graph
---


# Question
Title: setting a time delay between two frame when animation a sprite sheet
this is my jsfiddle :http://jsfiddle.net/Z7a5h/

As you can see the animation of the sprite sheet when the player is not moving is too fast so i was trying to make it slow by declaring two variable `lastRenderTime: 0,RenderRate: 50000`

but my code is not working and it seem i have a misunderstanding of the algorithm i am using so can anyone lay me a hand to how can i fix it ?

```
 if (!this.IsWaiting) {
                    this.IsWaiting = true;
                    this.Pos = 1 + (this.Pos + 1) % 3;

                }
                else {
                    var now = Date.now();
                    if (now - this.lastRenderTime < this.RenderRate) this.IsWaiting = false;
                    this.lastRenderTime = now;

                }

```

# Answer
> 1 votes
There's two issues in your code.

Firstly, you update the `lastRenderTime` at each iteration so `now - this.lastRenderTime` has always more or less the same value (the time between now and the last iteration).
Your assignation (`this.lastRenderTime = now`) should be inside your `if` brackets.

Secondly, you're doing your comparison the wrong way. you should check if the time since the last image change is greater than your `RenderRate`: `now - this.lastRenderTime >= this.RenderRate` but you're doing the opposite.

Due to these issues, your condition is always true and, then, the image changes at every single iteration.

---
Tags: javascript, html5, jquery
---


# Question
Title: How can I translate a game object towards a position?
I am instantiating my game objects (spheres) through scripts. I want my spheres to move from one location to another. but I don't know how to do this. `Update` is called once per frame. Is that what I should use? I am using the free version of Unity; I don't want to use special plugins.

How do I move these game objects from one location to another, over time?

# Answer
Yes, the `Update` loop is ideal for this. There are no special plug-ins required and you can do this with the free version. Basically you move the objects a tiny bit towards their destination each frame. When all those frames run one right after the other, it gives the appearance of smooth movement. A self contained script would look like the one I've created below. Ideally you'd take this as a starting point, and update it to use your own speed and starting point.

```
//move towards a target at a set speed.
private void MoveTowardsTarget() {
    //the speed, in units per second, we want to move towards the target
    float speed = 1;
    //move towards the center of the world (or where ever you like)
    Vector3 targetPosition = new Vector3(0,0,0);

    Vector3 currentPosition = this.transform.position;
    //first, check to see if we're close enough to the target
    if(Vector3.Distance(currentPosition, targetPosition) > .1f) {
        Vector3 directionOfTravel = targetPosition - currentPosition;
        //now normalize the direction, since we only want the direction information
        directionOfTravel.Normalize();
        //scale the movement on each axis by the directionOfTravel vector components

        this.transform.Translate(
            (directionOfTravel.x * speed * Time.deltaTime),
            (directionOfTravel.y * speed * Time.deltaTime),
            (directionOfTravel.z * speed * Time.deltaTime),
            Space.World);
    }
}

```

This code could be anywhere (for now just put it inside the script you're using it from). Tn the script attached to the sphere you want to move, you'd put: `MoveTowardsTarget()` in the `Update()` function.
> 11 votes

---
Tags: unity, movement, transformation
---


title: How do I handle DirectX mouse events?

text:
# Question
Title: How do I handle DirectX mouse events?
I am a beginner making my second game (simple low graphics FPS), in *Visual C++ 2010*. So far, I only know how to use keyboard controls. I've had source files like `keyboard.h` and `keyboard.ccp`, responding to callback functions like `kbd.UpIspressed()`.

How can I do this with mouse controls?

# Answer
> 3 votes
If you're using win32 then you can handle mouse and keyboard events using RawInput. Info can be found on MSDN.

You would handle windows messages for raw input devices in the window process. For example, if handling the input for a keyboard and mouse, register those devices in the WM\_CREATE case of your application window process like so:

```
switch( uMsg ){
case WM_CREATE:
{
    // register raw input devices
    RAWINPUTDEVICE rID[2];

    // Keyboard
    rID[0].usUsagePage = 1;
    rID[0].usUsage = 6;
    rID[0].dwFlags = 0;
    rID[0].hwndTarget=NULL;

    // Mouse
    rID[1].usUsagePage = 1;
    rID[1].usUsage = 2;
    rID[1].dwFlags = 0;
    rID[1].hwndTarget = hWnd;
    if ( !RegisterRawInputDevices( rID, 2, sizeof( RAWINPUTDEVICE ) ) )
    {
        // handle failure
    }
    ...
    break;
}

```

Then in the same process handle the raw input messages with WM\_INPUT like so:

```
switch( uMsg )
{
    ...
    case WM_INPUT:
    {
        RAWINPUT *pRI = NULL;

        // Determine how big the buffer should be
        UINT iBuffer;
        GetRawInputData( ( HRAWINPUT )lParam, RID_INPUT, NULL, &iBuffer, sizeof( RAWINPUTHEADER ) );

        // Allocate a buffer with enough size to hold the raw input data
        LPBYTE lpb = new BYTE[ iBuffer ];
        if( lpb == NULL )
            return 0;

        // Get the raw input data
        UINT readSize = GetRawInputData( ( HRAWINPUT )lParam, RID_INPUT, lpb, &iBuffer, sizeof( RAWINPUTHEADER ) ) ;

        // Validate that read size is as expected
        if( readSize != iBuffer )
            puts( "ERROR: GetRawInputData didn't return correct size!" ) ;
        pRI = ( RAWINPUT* )lpb;

        // Process the Mouse Messages
        if( pRI->header.dwType== RIM_TYPEMOUSE )
        {
            raw.riProcessMouseMessage( &pRI->data.mouse );
        }

        // Process the Keyboard Messages
        if( pRI->header.dwType== RIM_TYPEKEYBOARD )
        {
            raw.riProcessKeyboardMessage( &pRI->data.keyboard );
        }

        // Destroy the Raw Input Data and Return
        SAFE_DELETE( lpb );
        return 1;
    }
}

```

The 'raw.riProcessMouseMessage() and raw.riProcessKeyboardMessage() functions come from a class I use to keep track of raw input keyboard and mouse states...I found this on a raw input tutorial( that I can't find right now ). Here are the function definitions:

```
USHORT keyState[256];
short mouseState[5];
short mzr;
long mxr, myr;

USHORT MASKDOWN[ 5 ] = { RI_MOUSE_LEFT_BUTTON_DOWN,
RI_MOUSE_RIGHT_BUTTON_DOWN,
RI_MOUSE_MIDDLE_BUTTON_DOWN,
RI_MOUSE_BUTTON_4_DOWN,
RI_MOUSE_BUTTON_5_DOWN };

USHORT MASKUP[ 5 ] = { RI_MOUSE_LEFT_BUTTON_UP,
RI_MOUSE_RIGHT_BUTTON_UP,
RI_MOUSE_MIDDLE_BUTTON_UP,
RI_MOUSE_BUTTON_4_UP,
RI_MOUSE_BUTTON_5_UP };

void riManager::riProcessMouseMessage( const RAWMOUSE *rmouse )
{
    // Store Mouse Button States
    for(int i = 0; i < 5; i++)
    {
        if( MASKDOWN[ i ] & rmouse->usButtonFlags )
            mouseState[ i ] = 1;
        else if( MASKUP[ i ] & rmouse->usButtonFlags )
            mouseState[ i ] = 0;
    }
    // Check Mouse Position Relative Motion
    if ( MOUSE_MOVE_RELATIVE == rmouse->usFlags )
    {
        mxr = rmouse->lLastX ;
        myr = rmouse->lLastY ;
    }

    // Check Mouse Wheel Relative Motion
    mzr = ( RI_MOUSE_WHEEL & rmouse->usButtonFlags ) ? ( short )( rmouse->usButtonData ) : 0;
}
void riManager::riProcessKeyboardMessage( const RAWKEYBOARD *rkey )
{
    // Store New Key State
    keyState[ rkey->VKey ] &= 0xfe;
    keyState[ rkey->VKey ] |= 1 - ( RI_KEY_BREAK & rkey->Flags );
}

```

It will be up to you to manage these variables. Build a class to hold the variables, then you can access the key and mouse states at will.

# Answer
> 0 votes
Somewhere in your code you should already have a message pump. Simply add `WM_MOUSEMOVE` as one of the message types you handle and check the message parameters to determine mouse position. Alternatively, you can use raw input if you want to support ultra low-latency or sub-pixel motion.

---
Tags: c++, directx, mouse
---


# Question
Title: Can I optimize my voxel meshing regardless of different textured blocks?
At the moment, I mesh every voxel in my terrain data to a block with 4 vertices for each face. This makes assigning texture coordinates of my texture atlas very easy, since I can just pick the desired part for each face independently.

Unfortunately, rendering a bigger amount of such terrain chunks becomes very slow because of the unoptimized meshes. Therefore I want to redue the number of faces and vertices produced by the meshing algorithm. This is an image I found on the web showing what an optimized mesh could look like.

Grouping faces of different voxels make me think of how to still handle distinctive textures for each block. Is my worry right and how can this be handled?

# Answer
I put together a greedy meshing implementation for voxel data which includes various attributes (https://www.youtube.com/watch?v=0OZxZZCea8I). I understand you're looking to merge voxel faces even when they aren't the same voxel type - but it would seem that the only way to do that is to send the set of voxel types represented by the quad into the shader and then work out the texture coordinates for each point on the fragments by referring to this data and offsetting read from the texture atlas.

I didn't do this - instead I only merge voxel faces that are exactly equal, including lighting data - but it might be possible. The problem, I would think, would be that you'd be increasing the size of your vertex buffers, thus losing some of the gains of greedy meshing in the first place - and, of course, adding calculation to your shaders. Also, if you do need to light the mesh using any kind of baked ambient occlusion, you might also find that splitting up the quads by lighting values is necessary in any case.

Best of luck!
> 4 votes

# Answer
In theory (untested), the fallowing could work. Might vary depending on the Graphics Pipeline.

Assuming you are using custom shaders. The basic concept (in my probably failing attempts to explain it) is to take the world position of each fragment, and use that to generate your texture coordinates. Those coordinates ranging from (0,0) to (1,1), representing an entire image. Say you wanted 1/1 unit/image ratio (the image repeated once for every unit of space), In GLSL:

```
vec3 worldTexCoord = fract(vertexPosition.xyz); // 1 unit in the game world will
                                                // vary from (0,0) to (1,1) in TexCoords

```

You could then transform that into a smaller portion of the atlas. So then, instead of repeating an entire image, only the small portion of the image could be repeated.

```
vec2 trueTexCoord = mix(texCoordMin.xy, texCoordMax.xy, worldTexCoord.xy);

```

So then, if you want the image to repeat from the texture-coordinates `(0.1,0.1)` to `(0.5,0.5)` (instead of `(0,0)` to `(1,1)`), you would set `texCoordMin.xy = vec2(0.1, 0.1)` and `texCoordMax.xy = vec2(0.5, 0.5)`

You could also say `texCoordMax.xy = texCoordMin.xy + vec2(0.4, 0.4)` and get the same result as above.

So, after probably failing at that explanation, here is an overview.

1. Pass Vertex Position (in world coordinates) to the fragment/pixel shader
2. Use the Vertex Position to generate the texture-coordinates.
3. Manipulate the Vertex Position coordinates into coordinates relative to a smaller portion of the image, as indicated by the Texture Coordinates.

---

Sorry, scratch that.

Personally, I would suggest Sparse-Voxel-Octrees (SVO) if your looking to optimize your meshes. It works by clumping up large chunks formed of the same type of terrain. (Air, dirt, etc) so you wind up with, not only an optimized mesh, but a memory efficient structure, which could double as a Space Partitioning Tree for whatever else you may do.

Another thing usually done, is RLE (Run Length Encoding), it is used in BMP images to unify strips of similar colors from `X color, X color, X color, ...` down to saying `X color is repeated Y times`, reducing the required space when stored on your hard-drive. That get's interpreted when rendering Voxels as `X textured polygon is Y times it's usual length`

What does the guy in that image use? Looking at it, I would guess an SVO. It seems to have some resemblance. Large polygons for flat surfaces, little squares around corners that vary from `solid` type to `air` type. Though his flat surfaces do tend to be more rectangular, with less of an identifiable structure. could be some further optimizations on his part. But he doesn't actually texture the terrain, so can't actually know if there are multiple voxel types per polygon.
> 2 votes

---
Tags: voxels, vbo, texture-atlas
---


# Question
Title: Unity 4.3 (2D) Rendering only the parts of a sprite that are within specific bounds
I'm working in Unity, using the 2D features to recreate the match-3 style of 10000000 (Ten Million).

I have a parent object (green square) with several children objects (blue rectangles) on top of it, as pictured in the first image. I want to only render the parts of the child objects that are over top of the parent object, as shown in the second image.

I can figure out the size and position of everything just fine, what I'm having trouble with is figuring out how to mask off the parts of the child objects that don't overlap with the parent.

# Answer
Use a shader with an alpha mask. The Unify Community Wiki has an excellent alpha mask shader, and it's remarkably simple to use. I've done a few tricks with stuff like this (such as making a "night" scene with lighting by putting a semi-transparent overlay over the scene, and using alpha-masking to "cut out" the overlay, where there was light).
> 1 votes

---
Tags: c#, unity, sprites, masking
---


# Question
Title: How can I create a bomb explosion in Farseer that pushes nearby objects away?
I'm trying to create a bomb explosion in Farseer. I created a circle for the bomb. However, if the bomb explodes, the objects (bodies) that are around it should fly away because they're pushed back by the enormous force of the explosion. I'm not sure how to create that force, though - how can I do it?

# Answer
I would recommend checking out the explosion iforce2d page. It does a great job going over the various ways of handling explosions with the performance vs. accuracy tradeoffs. It goes over 3 methods which I will summarize here. So this is simply me summarizing information I found while researching and none of it is my own work.

Also you want to apply impulses here not forces. To understand why read this.

## The Proximity method

This is the same method that Byte56 goes over in his answer. The concept is simple. Have an explosion point and apply an impulse in the opposite direction away from the point which will affect all objects with a strength based on their distance away.

Pros:

* Very fast
* Easy to code.

Cons:

* Explosions pass through immovable objects and static bodies.
* Objects that are in the influence area of the blast may be skipped if you only check the distance to the center of mass.
* Surface area is not taken into account.
* Everything is affected at once.

## The Raycast method

This one is simple enough, cast out rays from the origin of your explosion and apply impulses when they collide into an object with an impulse dictated by the distance.

Pros:

* Less performance intensive than the projectiles method.
* Explosion blocked by objects.
* Surface area taken into account.

Cons:

* Everything is affected at once.
* The larger the explosion the more rays you need to make sure the explosion affects everything.
* More performance intensive than the proximity method.

## The Particle method

My personal favorite. Similar to the RaySasting method but instead of rays you leverage the physics engine and spit out small pellets that interact with your scene.

Pros:

* Extremely easy code-wise. Generate the balls and apply an impulse to each one. You have no code to write per tick. Just have a timer that goes though and disables/resets the bodies after the explosion is complete.
* Explosion is blocked by objects.
* Surface area is taken into account.
* Explosion reflects off of surfaces.
* Objects further from the blast respond to it more slowly.
* You can use the balls as the basis for generating partials allowing your effects to accurately reflect the explosions impact.

Cons:

* Adds per-tick complexity.
> 28 votes

# Answer
* Select all the objects within the bomb's radius of influence.
* For each object
    + Use the object position and the center of the explosion to calculate the vector of the impulse. Something like `normalize(object - center)`.
    + Use the distance from the center of the bomb to the object to calculate the magnitude of the impulse. Something like `(object - center).length`
    + Apply an impulse to the object using the vector and magnitude found in the previous steps.

As for calculating the magnitude you can start of with simple linear falloff, then move to other formulas if you don't like the results.
> 2 votes

---
Tags: xna, c#, farseer-physics-engine
---


# Question
Title: How can I get multiple sprites on a Unity2D Sprite Renderer
I have a GameObject that I want to have multiple sprites. I tried adding an extra Sprite Renderer, but it tells me I can't add the same component multiple times.

I'd really rather not have to have four GameObjects just to display this thing correctly.

For example, I would want to have a tile background, a tile artwork, a tile character, and a nice shine on the top. If I were to make that all a single image, I would have to export nearly a thousand images to get all possible combinations.

Tile Background:

Tile Artwork:

Tile Character:

Shine (Barely visible):

Everything put together how I want it in-game:

# Answer
Yes, you'll need to have a single game object for each sprite, but you'll only have as many game objects as you have layers.

So you'd create a game object with the following children (and save it as a prefab):

You can then have a script that changes the sprite for each layer:

```
public class Icon : MonoBehaviour
{
    public SpriteRenderer artwork;

    public void SetArtworkSprite(Sprite art)
    {
        artwork.sprite = art;
    }
}

```

The Icon script would be in the Icon game object and would have all its fields linked with the child game objects. So then you can have an icon generator script as so:

```
public IconGenerator : MonoBehaviour
{
    public Icon iconPrefab;

    public void CreateIcon(...)
    {
          Icon newIcon = Instantiate(iconPrefab) as Icon;
          newIcon.SetArtworkSprite(...);
          newIcon.SetBackgroundSprite(...);
          [...]
    }
}

```

If you REALLY need everything to be a single game object, than I believe you can achieve this by creating a shader that takes X textures and renders them. But I'm not sure if it's worth it.
> 8 votes

---
Tags: unity, sprites
---


# Question
Title: Event-driven Communication in a Game Engine: Yes or No?
I am reading *Game Coding Complete* and the author recommends *Event Driven communication* among game objects and modules.

Basically, all living game actors should communicate with the key modules (Physics, AI, Game Logic, Game View, etc.) via an internal event messaging system. This means having to design an efficient event manager. A badly designed system eats CPU cycles, especially affecting mobile platforms.

Is this a proven and recommended approach? How should I decide whether to use it?

# Answer
This is an expansion of my comment to a full answer, as suggested.

*Yes*, plain and simple. Communication needs to happen and while there are situations where *'Are we there yet?'*-type polling is required, having things check to see if they should be doing something else generally wastes time. You could instead have them react to things they are told to do. Plus, a well defined communication pathway between objects/systems/modules boosts parallel setups significantly.

I've given a high-level overview of an event messaging system over on Stack Overflow. I have used it from school into professional gaming titles and now non-gaming products, adapted to the use case every time of course.

*EDIT*: To address a comment question on *how do you know which objects should get the message*: The objects themselves should `Request` to be notified about events. Your `EventMessagingSystem` (EMS) will need a `Register(int iEventId, IEventMessagingSystem * pOjbect, (EMSCallback)fpMethodToUseForACallback)` as well as a matching `Unregister` (making a unique entry for an `iEventId` out of the object pointer and callback). This way, when an object wants to know about a message it can `Register()` with the system. When it no longer needs to know about the events, it can `Unregister()`. Clearly, you'd want a pool of these callback registration objects and an effective way to add/remove them from lists. (I've usually used self ordering arrays; a fancy way of saying they track their own allocations between a pool stack of unused objects and arrays that shift their sizes in place when needed).

*EDIT*: For a completely working game with an update loop and an event messaging system, you might want to check out an old school project of mine. The Stack Overflow post linked above also refers to it.
> 50 votes

# Answer
My opinion is that you should just start making your game and implement what you're comfortable with. As you do that you'll find yourself using MVC some places, but not others; events some places, but not others; components some places, but inheritance others; clean design some places, and crufty design others.

And that's OK, because when you're done you'll actually have a game, and a game is way cooler than a message-passing system.
> 23 votes

# Answer
Messages generally work well when:

1. The thing sending the message doesn't care if it gets received.
2. The sender does not need to get an immediate response back from the receiver.
3. There may be multiple receivers listening to a single sender.
4. Messages will be sent infrequently or unpredictably. (In other words, if every object needs to get an "update" message every single frame, messages aren't really buying you much.)

The more your needs match that list, the better of a fit messages will be. At a very general level, they're pretty good. They do a good job of not wasting CPU cycles just to do nothing unlike polling or other more global solutions. They are fantastic at decoupling parts of a codebase, which is always helpful.
> 19 votes

# Answer
A better question is, what alternatives are there? In such a complex system with properly divided modules for physics, AI, etc., how else can you orchestrate these systems?

Message passing does seem to be the "best" solution to this problem. I can't think of alternatives right now. But there are plenty of examples of message passing in practice. In fact, operating systems use message passing for several of their functions. From Wikipedia:

> Messages are also commonly used in the same sense as a means of interprocess communication; the other common technique being streams or pipes, in which data are sent as a sequence of elementary data items instead (the higher-level version of a virtual circuit).

(Interprocess communication is the communication between processes (i.e. running instances of programs) within the operating system environment)

So if it's good enough for an operating system, it's probably good enough for a game, right? There are other benefits as well, but I'll let the Wikipedia article on message passing do the explaining.

I also asked a question on Stack Overflow, "Data structures for message passing within a program?", which you might want to read over.
> 18 votes

# Answer
Great answers so far from James and Ricket, I only answer to add a note of caution. Message passing / event driven communication is certainly an important tool in the developer's arsenal, but it can easily be overused. When you have a hammer, everything looks like a nail, and so on.

You absolutely, 100%, should be thinking about the flow of data around your title, and be fully aware of how information is passing from one subsystem to another. In some cases message passing is clearly best; in others, it may be more appropriate for one subsystem to operate over a list of shared objects, allowing other subsystems to also operate on the same shared list; and many more methods besides.

At all times you should be aware of which subsystems need access to which data, and when they need to access it. This affects your ability to parallelise and optimise, as well as helping you avoid the more insidious problems when different parts of your engine become too closely entwined. You need to be thinking about minimising unnecessary copying around of data, and how your data layout affects your cache usage. All of which will guide you to the best solution in each case.

That being said, pretty much every game I've ever worked on has had a solid asynchronous message passing / event notification system. It allows you to write succinct, efficient maintainable code, even in the face of complex and quickly changing design needs.
> 7 votes

# Answer
**Yes.** It is a very efficient way for game systems to communicate with each other. Events help you decouple many systems and make it possible to even compile things separately without knowing of each others' existence. This means your classes can be more easily prototyped and the compilation times are faster. More importantly, you end up with a flat code design instead of a dependency mess.

Another big benefit of events is that they are easily streamed over a network or other text channel. You can record them for later playback. The possibilities are endless.

Another benefit: You can have several subsystems listening for the same event. For example, all your remote views (players) can automatically subscribe to the entity creation event and spawn entities on each client with little work on your part. Imagine how much more work it would be if you did not use events: you would have to place `Update()` calls somewhere or maybe call `view->CreateEntity` from the Game logic (where knowledge about the view and what information it requires doesn't belong). It's hard to solve that problem without events.

With events you get an elegant and decoupled solution that supports infinite number of objects of unlimited kinds that can all simply subscribe to events and do their thing when something happens in your game. That's why events are great.

More details and an implementation here.
> 5 votes

# Answer
Well, I know that this post is quite old , but I could not resist.

I recently built a game engine. It uses 3d party libraries to rendering and physics, but I wrote the core part, that defines and processes the entities and game logic.

The engine surely follows a traditional approach. There is a main update loop that calls update function for all entities. Collisions are directly reported by callback on the entities. Communications between entities are made using smart pointers exchanged between entities.

There is a primitive message system, That processes only a small group of entity to engine messages. Those messages are preferable to be processed at the end of a game interaction ( example is a entity creation or destruction ) because they can mess with the update list. So , at the end of each game loop, a small list of messages are consumed.

Despite the primitive message system , I would say that the system is largely "update loop based".

Well. After using this system, I think that it is very simple, fast and well organized. The game logic is visible and self contained inside entities, not dynamic like a message quewe. I really would not to make it event driven because in my opinion event systems introduce unnecessary complexity to the game logic , and make the game code very difficult to understand and debug.

But, I also think that a pure "update loop based" system like mine have some problems too.

For example, In some moments, one entity may be at a " do nothing state " , may be waiting the player approaching or something else. In most of those cases , the entity burns processor time for nothing and its is better to turn the entity off, and turn it on when a certain event happens.

So, in my next game engine , I am going to adopt a different approach. Entities will register themselves for engine operations, like update, drawing, collision detection and so one. Each of these events will have separated lists of entity interfaces for the actual entities.
> 4 votes

# Answer
From what I have seen, it doesn't seem to be very common to have an engine completely based on messaging. Of course, there are subsystems which lend themselves very well to such a messaging system, like networking, GUI, and possibly others. In general though, there are a few problems I can think of:

* Game engines deal with large amounts of data.
* Games have to be fast (20-30 FPS should be the minimum).
* Often it is necessary to know if something has been done or when it will be done.

With the common game developer approach of "it has to be efficient as possible" such messaging system are thus not that common.

However, I agree that you should just go ahead and try it. There certainly are lots advantages with such a system and computing power is cheaply available today.
> 2 votes

---
Tags: architecture, software-engineering, events
---


# Question
Title: Recommend a way to draw thousands of particles (liquid) per frame in Unity3d
I'm writing a plugin for this library for Unity3d. I have it working and now I am looking for an efficient way to draw the particles. My 1st test just uses sprites and runs fine on my laptop but I doubt it will be so good on a mobile device.

Is there a cheap way of simply drawing lots of particles to the screen each frame? The library generates an array of all the particle positions which updates in FixedUpdate() so I can just draw everything in that array each frame.

I'm thinking maybe somehting in the Graphics namespace would handy here, like maybe Graphics.DrawTexture

Also I might consider doing some kind of metaballs like pass over the particles to make them look more liquid like.

# Answer
Generally, quads can be replaced by triangles to save computational power.

Since a quad is made of two triangles, you can simply make a bigger triangle that will encompass the whole particle texture (if any) and add it a transparency shader.

You'll get an instant decrease of geometry computation by 50% compared to an all-quad system, for exactly the same result.
> 2 votes

# Answer
Try to use point primitives. It should be the fastest possible solution, you use just position for rendering, but you can set the point size and even a shader/texture, so it may look almost like a mesh.

If you want to go even further you can render this on some off-screen texture to make some post-processing, like edge detection or better normal creation - this way you'll get almost countless possibilities to get the look you want.
> 0 votes

---
Tags: unity, rendering, particles
---


title: DirectX Bullet Tracer Effect

text:
# Question
Title: DirectX Bullet Tracer Effect
I'm wondering if anyone knows some common and efficient ways to do a fast tracer for an instant bullet.

I've seen people speak on forums of using primitive lines with DirectX, but I doubt this is up to "Commercial" standards. I also thought of using some sort of minimal prism geometry encompassing the line and using a shader but even then, I'm not sure how to give it that nice glow and fade. I'm obviously not looking for any code in specific, just some ideas in general.

Thanks, Joey

# Answer
There are billion ways to do this. But here is my approach :

To do this i would go with a more "particle" system approach. Rendering a line is quite easy with a quad, you just stretch the four vertex in the direction it´s traveling and then have a maximum length that it never can be longer than.

the best way with this is that you can heayily optimize this to the GPU and do most of the code on the vertex shader which will be immensely fast. You could even go so far that you just set up a bunch of points that you update on the cpu side. Which would be the point where the bullet is, and then just stretch the "back" vertex´s to the negative direction * length. that would give you a line, then you just have to make sure it´s always facing the camera. With that you can apply textures and other cool effects like heat daze or what not.

This is a very trivial task and should be very straight forward to. Good luck!
> 2 votes

---
Tags: opengl, 3d, directx, graphics, shooter
---


# Question
Title: Unity objects not rotating around pivot point
Suddenly, for some reason, objects in the unity editor started rotating around their center of gravity (at least that's what I think is going on) instead of their pivot point. I tried placing the object inside an empty object which would serve as the new pivot point, like usual, but this did not change anything. Is this some setting or some updated feature? How can I stop it?

# Answer
This could be related to the 4.1, 4.2 and 4.3 updates when they added 2D support.

Objects can be defaulted to an average pivot point of itself and child objects instead of the specific pivot of the item selected. There is a setting you can change on the toolbar to show you which pivot you currently have displayed.

This affects what the pivot point is for all transforms within the editor:
> 1 votes

---
Tags: unity, rotation
---


title: LibGDX cannot save to internal file

text:
# Question
Title: LibGDX cannot save to internal file
I want to save the state of the game in a file, so I can read it at the next start. The Problem is, that I get a exception, if I try to save something internal. If I try to save it local all work fine. I save the file as a Json.

```
Bird bird = new Bird();
bird.setName("Foo");
bird.setSkin(new Texture("data/foo.png"));
bird.save(Gdx.files.internal("bird.json"));

```

The save mthod:

```
Json json = new Json();
file.writeString(json.prettyPrint(this), false);

```

> Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeException: Error writing file: bird.json (Internal) at com.badlogic.gdx.files.FileHandle.writeString(FileHandle.java:349) at com.badlogic.gdx.files.FileHandle.writeString(FileHandle.java:335) at com.buschmannmichael.fattybird.core.Bird.save(Bird.java:31) at com.buschmannmichael.fattybird.game.FattyBirdGame.create(FattyBirdGame.java:16) at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:137) at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:115) Caused by: com.badlogic.gdx.utils.GdxRuntimeException: Cannot write to an internal file: bird.json at com.badlogic.gdx.files.FileHandle.writer(FileHandle.java:315) at com.badlogic.gdx.files.FileHandle.writeString(FileHandle.java:346) ... 5 more

Whats the problem of LibGDX, where I should save the files, so I can run the game on android, desktop and html ? (I tested this method I showed above only on desktop, maybe it works on android but I want a solution for all platforms)

Maybe someone can help me :)

# Answer
Gdx.file.internal is **read-only**. You can use ***local*** file or ***preferences*** (creates an internal .xml file where you can store small amount of data). It is perfect for game saving.

Take a look at : https://github.com/libgdx/libgdx/wiki/Preferences

You can also use an external file (stored on sdcard), but you can optionally encrypt it, as it can be edited by the user.
> 6 votes

---
Tags: android, libgdx
---


title: 3D Camera Rotation

text:
# Question
Title: 3D Camera Rotation
Please, forgive me, but I need help and I've been stuck on this for a few weeks now, I'm making no progress and everywhere I go and I see a different answer, everything I try doesn't work. I've had enough tips and advice, now I really just need someone to give me the answer for me to work backwards from because I can't understand this.

What has made this subject most confusing is the way everyone uses a different set of conventions or rules, and their answers are based on their own conventions without defining what they are.

So here is the set of conventions I've formed based on what seems to be most common and logical:

1. Right Hand Rule for axis.
2. Positive Y is up, Positive Z is towards the viewer, Positive X is to the right.
3. Row Major matrixes, transposed when sent to shaders.
4. * Pitch: rotation about the X axis
    * Yaw: rotation about the y axis
    * Roll: rotation about the z axis
5. Rotation order: Roll, Pitch, Yaw (is this correct? can someone check me on this?)
6. Positive rotation values, looking down from positive end of an axis, results in clockwise rotation.
7. Default direction for 0 rotation across all axis is a vector pointing down to negative Y.

.. given those conventions (by all means correct me if they are wrong!), how does one:

* Write a LookAt function? (lookAt(vector position, vector eyefocus, vector up))
* Calculate a rotation matrix. (rotation(x, y, z))

I've tried answering these two questions myself at least over the past 3 weeks, I've re-written my LookAt & Rotation Matrix function at least 30 times, I've tested dozens of methods and read through material I've seen on hundreds of websites and read many answered questions, copied other people's code, and nothing I've made so far has worked, everything has produced the wrong result. Some of which have produced some hilariously bizarre outputs not even close to correct rotation.

I've been working on this every night with the exception of last night because I was getting so frustrated with the repeated failure that I had to stop and take a break.

Please, just show me what the correct method is so I can work backwards from that and figure out how it works, I'm just not getting the correct answer and this is driving me a little crazy!

I'm writing in Java but I'll take code written in any language, most of my 3D rendering code is actually working quite brilliantly, it's just the maths I can't understand.

UPDATE: SOLVED

Thankyou for your help! I now have a working LookAt function that I actually understand and I couldn't be happier (if anyone would like to see it by all means ask).

I did try again at creating a rotation matrix based off pitch/yaw/roll variables and it again seemed to fail, but I've decided to dump attempting to use euler angles for the freelook camera as it seems to be ill-suited for the role, instead I'm going to create a quaternion class, might have better luck going down that path, otherwise I'll resort to using the pitch/yaw as spherical coordinates and rely on the new working LookAt function for rotation.

If anyone else is facing a similar problem and wants to ask me questions, feel free to.

At least I'm not stuck anymore, thanks for the help!

# Answer
> 16 votes
What you are looking for can be found in this very good explanation: http://www.songho.ca/opengl/gl\_transform.html

But since I found it sort of confusing without hand holding I will try to explain it here.

At this point you need to consider 5 coordinate systems and how they relate to each other. These are the window coordinates, the normalized device coordinates, the eye coordinates, the world coordinates and the object coordinates.

The window coordinates can be seen as the "physical" pixels on your screen. They are the coordinates that the windowing system refers to and if you operate in your monitors native resolution, these are actually individual pixels. The window coordinate system are 2D integers and is relative to your window. Here the x+ is left and y+ is down with the origin at the top left corner. You encounter these when you for example call `glViewport`.

The second set are the normalized device coordinates. These refer to the space setup by the active view port. The visible area of the view port goes from -1 to +1 and thus has the origin in the center. The x+ is left and the y+ is up. You also have the z+ is "out" of the scene. This is what you describe in 1.

You have no control how you get from the normalized device coordinates to the window coordinates, this is done implicitly for you. The only control you have is through `glViewport` or similar.

When working with openGL, your final result will always be in normalized device coordinates. As a result you need to worry how to get your scene rendered in these. If you set the projection and model-view matrix to the identity matrix you can directly draw in these coordinates. This is for example done when applying full screen effects.

The next is the eye coordinates. This is the world as seen from the camera. As a result the origin is in the camera and the same axis aliments like the device coordinates apply.

To get from the eye coordinates to the device coordinates you build the projection matrix. The simplest is the orthographic projection that just scales the values appropriately. The perspective projection is more complicated and involves simulation perspective.

Finally you have the world coordinate system. This is the coordinate system in which your world is defined and your camera is part of this world. Here it is important to note that **the axis orientations is just as you define them**. If you prefer z+ as up, that is totally fine.

To get from world coordinates to eye coordinates you define the view matrix. This can be done with something like `lookAt`. What this matrix does is "move" the world so that the camera is at the origin and looking down the z- axis.

To compute the view matrix is surprisingly simple, you need to unto the camera's transformation. You basically need to formulate the following matrix:

$$ M = \begin{matrix} x\[1\] & y\[1\] & z\[1\] & -p\[1\] \\ x\[2\] & y\[2\] & z\[2\] & -p\[2\] \\ x\[3\] & y\[3\] & z\[3\] & -p\[3\] \\ 0 & 0 & 0 & 1 \end{matrix} $$

The x, y and z vectors can be directly takes from the camera. In the case from look at you would derive them from the target, eye(center) and up values. Like so:

$$ z = normalize(eye - target) \\ x = normalize(up \times z) \\ y = z \cdot x $$

But if you happen to have these values just lying around you can just take them as they are.

Getting p is a bit more tricky. It is not the position in world coordinates but the position in camera coordinates. A simple workaround here is to initialize two matrixes, one with only x, y and z and a second one with -eye and multiply them together. The result is the view matrix.

For how this may look in code:

```
mat4 lookat(vec3 eye, vec3 target, vec3 up)
{
    vec3 zaxis = normalize(eye - target);
    vec3 xaxis = normalize(cross(up, zaxis));
    vec3 yaxis = cross(zaxis, xaxis);

    mat4 orientation(
       xaxis[0], yaxis[0], zaxis[0], 0,
       xaxis[1], yaxis[1], zaxis[1], 0,
       xaxis[2], yaxis[2], zaxis[2], 0,
         0,       0,       0,     1);

    mat4 translation(
              1,       0,       0, 0,
              0,       1,       0, 0,
              0,       0,       1, 0,
        -eye[0], -eye[1], -eye[2], 1);

    return orientation * translation;
}

```

full code

And finally for the sake of completeness, you also have the object coordinate system. This is the coordinate system in which meshes are stored. With the help of the model matrix the mesh coordinates are converted into the world coordinate system. In practice the model and view matrices are combined into the so called model-view matrix.

---
Tags: opengl, java, 3d, mathematics, camera
---


# Question
Title: Is permission needed to use a living famous person as a character in a game?
If I wanted to sell an iphone game in which you play as a famous person, would that require permission from the famous person?

# Answer
> 1 votes
Now just as a heads up, we aren't lawyers and you shouldn't take advise from a forum website as legal advise.

Now to answer your question: **most likely**

It really depends on where you live and which laws govern it for any game. Such that if you live in India, you would need to look at local law.

Being released on iOS, you typically would also need to adhere to US law since Apple is based in the US.

So let's look at one fairly relevant example. In this case they won the lawsuit for using "likeness" without permission. That means that even without using their name, the characters in-game were close enough to their real-life counterparts that EA was forced to fork a lot of money.

Now let's look at a more recent example. In this case Lindsay Lohan is suing in a very similar fashion. Now if I remember correctly, this one never went anywhere. However is goes to illustrate that people being people will get upset when they aren't paid.

Now on the flip side of the matter is **publicity**. A small-time game may be able to get away with it. "If nobody knows, then nobody will sue me" is unfortunately too common. Although in case a game gets big, suddenly you get noticed, and likely shut down or sued.

# Answer
> 2 votes
Depends on factors such as whether you're making money (and who for), whether it's a parody, what country's laws apply, etc.

A parody game making money for charity in a country with very strong fair use doctrines is going to be different to an academic venture in a country without a concept of fair use.

We are not lawyers; ask a lawyer.

# Answer
> 0 votes
In short, ABSOLUTELY!

It's basically the same as stealing their name and everything they've worked for to say that they like and want to sponsor your game, when they probably don't.

Your best bet is most likely to make a character that looks similar without being an exact replica, then change the first name. This way you have a character that reminds your players of the famous character without actually using the famous person. It's not guaranteed to keep you from being sued but it's a much better option than using the person without permission.

---
Tags: ios, copyright
---


title: libGDX without android dependancies

text:
# Question
Title: libGDX without android dependancies
I want to create a game that due to some assumptions doesn't make sense as a tablet game.

I already created some frame (controllers, autowiring, build scripts, etc.) that would help me later on, but since Slick2D, that I currently basing it on, is no longer really supported I am considering switching to libGDX while it still not time expensive.

My question is: is it possible to easily get rid of all of Android dependencies? GUI scaffold generator doesn't allow to do that and I would like to know is it just generator's issue or is the library itself tied to Android dependencies?

It's my main concern that would help me decide whether or not switch from Slick.

EDIT:

Basically when I use GUI generator to scaffold project it creates at least 3 Eclipse projects:

* core project,
* Android project - depending on core,
* desktop project - depending on Android.

While it shouldn't a be problem to merge them into 1 bigger project and remove virtually dead code, I want to know if there would be left some Android dependencies that I couldn't remove to make it still runnable on desktop.

# Answer
Thanks for the comments -- I finally understand what you want.

TLDR: the summary of your question is encapsulated in the libGDX project setup page.

Essentially, libGDX has you create one "core" project (which is a standard Java project). Within it, you have your main game code.

Beyond that, you have wrapper projects (one per platform); these only call the main startup code from the core application.

For example, if you want a standard Java (Desktop) app and an Android app, you would have these projects:

* Core game (standard Java)
* Desktop wrapper
* Android wrapper

It's pretty versatile; I understand there's an iOS wrapper project now, too.
> 1 votes

---
Tags: libgdx, android
---


# Question
Title: Scene Graphs and Entity Component Systems
I am trying to determine how to move my current implementation of nodes in a scene graph to an entity component system and am struggling to wrap my head around how the two can work together, if at all.

I think the main cause of my confusion is breaking the habit of structuring everything in an object oriented hierarchy. I'm not overly familiar with game development as a whole so breaking what I already know works to replace with something else will be a testament to my knowledge.

Currently, I have a scene controller and a scene which handle the update and render loops accordingly. Code removed for brevity.

```
//scene controller
- (void)update:(NSTimeInterval)duration
{
    //loop though objects and integrate
}

- (void)render
{
    [[self scene] render];
}

//scene
- (void)render
{
    //loop through objects and render
}

```

This works fine with my scene nodes as is. Each node has properties for position, rotation, scale and geometry which are passed to shaders and rendered.

Now I am trying to remove all of these properties from the node and replace them with components.

**Note**: I realise that `node` means something else in an Entity Component System so this will be refactored into something else entirely.

It is my understanding that once I have transitioned from the current implementation to an ECS my game objects will expose the same position, rotation, scale and geometry properties but via components instead.

As of such, where will these new game objects sit in the hierarchy of a scene graph? My first thoughts would be to refactor the update and render loops to include the appropriate systems, a la:

```
//scene controller
- (void)update:(NSTimeInterval)duration
{
    //loop though objects and integrate
    [[self positionSystem] update:duration];
}

- (void)render
{
    [[self scene] render];
}

//scene
- (void)render
{
    //loop through objects and render
    [[self renderSystem] render];
}

```

However, it would seem odd to have the systems spread across two different objects (the scene controller and the scene). It would be possible remove the scene render loop and do this in the scene controller instead to keep everything in one place.

One final cause of confusion is how to link game objects together in the same way that my nodes are currently setup. A node can have children and a parent node which combine the parent matrices up the chain to allow me to link objects together, i.e.: a player and a sword.

From what I can gather, objects in an ECS shouldn't be linked together in this same way, or have I misunderstood the principles of an ECS? If this is the case, how would you create a scene graph from entities that aren't linked together in any way?

I'm eager to step back from my current implementation and overhaul the necessary parts but I'm not sure how to achieve a similar setup or if it is possible or even the correct way of doing things.

# Answer
Typically, your scene graph in an ECS (there's a lot of variations, but this is my take on it.) can be represented in a couple ways. The most popular way of doing this sort of thing and easiest is simply a list of 'Entities' that are attached. These Entities might have children/parents, they might not. It depends how you choose to model things.

In the most vanilla sense, your graph is usually nothing more than at it's simplest form a list of Entities which contains a list of components attached to them. These entities will each have things like "Transform", "Sprite", or even "CombatInfo" attached to them. Every discrete function should have a different component.

You can make your graph structure as complicated or simple as you'd like. If you require parenting, the ECS will not stop you from doing this. ECS is not meant to.
> 1 votes

---
Tags: entity-system, scene-graph, scene, entity-component
---


# Question
Title: How To Set Constants Using ID3DShaderReflection
I got to the point where I am tired of hardcoding shaders and decided that it was now time to look into using ID3D11ShaderReflection to get data from the shader and set my shader's constant buffer using that data. I have a simple system that loads up shaders and gets it's data. Now that I have the data, I would like to know how the correct way to upload the data to the constant buffer. I've searched on Google and couldn't find too much information on this. Any help? Thanks!

Here's some code: http://www.gamedev.net/topic/654950-setting-constants-using-id3d11shaderreflection/

# Answer
> 1 votes
The way I usually handle constant buffers is to define a struct in C++ that matches the layout of the constant buffer as defined in HLSL; then I can just create an instance of the struct and fill in the data.

You can also create a more data-driven system where you use the offset and size information retrieved from shader reflection. You'll need to allocate some memory the size of the buffer, then memcpy() individual variables into the correct spot based on the variable's offset. It looks like that's the direction you're heading based on your code snippets.

Either way, once your data is set up in the correct layout, before you do a draw call, you then map the constant buffer to get a pointer to the GPU-visible memory, and copy the data into it. This is done with the `ID3D11DeviceContext::Map()` method. For constant buffers, you should use `MAP_WRITE_DISCARD` for the third parameter. This way, the same buffer object can be re-used for multiple draws within the same frame without unnecessarily stalling the CPU.

When you're finished copying the data, unmap the buffer and bind it to the pipeline, and you're ready to draw.

(NB: you can also use `UpdateSubresource()` in place of `Map()` for updating constant buffers, but the performance could be worse due to an extra memory copy internally. `Map()` is considered best practice for updating constant buffers. See Efficient Buffer Management by John McDonald.)

---
Tags: c++, shaders, directx11, reflection-rendering
---


# Question
Title: What can make a peaceful game successful?
Today, the most successful games are action games like FPS, RPG, MMORPG...

I'd like to make a peaceful game, but I don't know how to attract people. I can make good graphics, but that's not the main thing that makes people like a game for more than a couple of minutes. The content is important. In the game styles mentioned earlier, their main content is fighting, killing others, and generally making yourself the most powerful player in the game.

But what content can attract people in a peaceful game?

# Answer
> 68 votes
You should probably have worded the question like this: **"What is/can be appealing in peaceful games?"**, and then used the answers as a general guide.

Moving on, essentially, you're answering the question: **"What interests/motivates/intrigues people in general, and isn't violent?"**

Here are some suggestions:

* In general, boys like **destruction** (I'm quoting Jesse Schell on this), so maybe you should find a way to make it non-violent (physics/chemistry simulation? Minecraft-like TNT?)
* Having any kind of **power** is a good feeling. Maybe you are a factory manager? A Sims City-like game can give a great sense of power, too.
* **Cooperation** is interesting and is a primal instinct, thus, it's very good to make use of it. So, consider multiplayer!
* Non-violent **competition** (competition being a primal instinct as well). Multiplayer gives you great posibillities here, as well.
* *(inspired by Byte's answer, and Jesse Schell)* People also enjoy **expression**. Art, building, any kind of **creative** activity is great!
* \[Add almost any other noun from that Maslow's pyramid here\]

See this updated Maslow's priority pyramid to find ideas:

Jesse Schell wrote a great book that will definitively help you: The Art of Game Design.

# Answer
> 17 votes
How to make a game successful is not something that can be answered. Other than being at the right place at the right time with the right game.

However, there are plenty of options for making a peaceful game.

* Puzzle games (Bejeweled)
* Word games (Words with friends)
* Art games (Draw something)
* Collaborative construction games (Minecraft)
* City building games (Sim city)
* And more: Exploration games, kids games, learning games, physics based games, pet care taking games and so on.

There are so many options. People do tend to relate game playing to violent video games, but there are actually far more games that are not violent.

# Answer
> 11 votes
Study the biggest group of people who do not understand violence - preschool children.

I have 3 of them (I am so lucky they are all good :D) and there is a lot to be learned from observing how they play, learn and interact.

* **Competitive** \- even at a young age they want to be better than their siblings.
* **Impressive** \- they love to copy things they see on TV and that their parents do. Writing, riding bikes...
* **Imaginative** \- they love stories that go beyond reality. That box on the floor is a boat this week; last week it was a roller coaster. When they play together they make up some bizarre adventures.
* **Simplicity** \- If a game is too complex or can't be explained in 30 seconds, they will lose interest.
* **Rewards** \- They will do stuff simply to get something shiny or sweet.
* Not sure how to label this, but they love to **do things they are not normally allowed to do**. Use Mummy's makeup, hit the keys on Daddy's laptop as he left the screen up.

There are probably more, but that is a selection of elements that could be rolled into a game to hook people that do not involve violence.

# Answer
> 6 votes
One thing most posters seems to have forgotten is **Exploration**. Lot of people likes that, might it be exploring a country or a complicated crafting system.

You might want to check out the Bartle Test which is one of the first studies on what drives players in multiplayer games, there is non-peacefully parts but most of it can be used to think up a peacefully game (for example: exclude the 'killers' and what they like: 'interacting on other players in a harmful way' and make it 'interact on other players in a peacefully way').

You might want to check out this Gamasutra article as well for ideas.

# Answer
> 5 votes
I think games are very much like movies in a sense. And for a movie to be good it doesn't have to be violent.

The big difference between a game and a movie is the interactive part (obviously). Also gamer's in general tend to want challenge and sometimes competition in games, which is not the case for movies.

But "necessary" mechanics of any game, violent or peaceful are:

**Achievements:** People need to chase something to stay interested, a (peaceful) game that hands you everything you can get from the start would get boring very fast. Example: If you could plant everything in FarmVille the first minute.

**Reward:** Once they've reached this goal they need satisfaction for the work. This could be a new feature, new items, whatever. Getting rewarded in a game activates the brains reward mechanism, which can get physically addictive, just like a drug.

**Scoreboard:** In today's society where everyone is judged by everyone this seems to give players alot of satisfaction, even when the only benefit is to showoff/brag. This could be counted in the reward part aswell, but I decided to put them separate.

These are three very basic mechanics that can be implemented into pretty ANY game. Now what you have to do is to decide what kind of a game you want to create, and based on that decide how you can implement all three of these mechanics to your game.

Other points i wont go deep into:

**Cooperation:** It's always fun to work togheter.

**Competition:** Always fun to beat your opponent.

**Mystery:** Keeps the player curious to what comes next.

I'll end the post there since it got very long, I hope this helps you to decide what kind of a game you want to create.

# Answer
> 3 votes
This is kinda backward. Conflict is necessary to build up tension, tension is required to make a compelling story. Violence is the easiest form of conflict. Most games try to tell a story and violence is the easiest way to archive that. You don't need to tell a story to make a game (a good story adds a lot the atmosphere though). The core component of a game still is the game-play. And the game-play rarely "needs" violence. For example a shooter could also be about a guy running through a parcour where he needs to hit all the targets once. Your game should be fun with or without violence, so think about that first and then think about violence. Not the other way arround.

# Answer
> 3 votes
The important point to understand is that it is good to have conflict in stories and games, but conflict does not mean fighting, war, killing or things like that. Also, collaboration (in conflict or not) is more rewarding to players on the long term.

# Answer
> 3 votes
Peaceful games typically value *creation* over competition. You progress your game by the types of this you've created instead of how many kills you've scored. Some examples:

* The Sims - You build up the life of a virtual character
* Minecraft - Your accomplishments are the things you've built (assuming non PVP mode)
* Sim City - You develop a virtual city

Your reward in these games is zooming way out on your digital creation and feeling pride about how cool it looks. For some people that's not really that compelling, for others it's all that matters.

# Answer
> 1 votes
The main things that attract people to the Harvest Moon series are

* curiosity (new environment to explore)
* social events, even side stories. family, friends etc.
* events or stories.
* new experience (farming)
* finally a goal (the game goal or a financial goal in the game) simply some success.
* and of course more freedom, less limitation or repetition + more choices.
* in-game secrets

---
Tags: game-design
---


# Question
Title: Handling XBox 360 Controller Connections in LibGDX after Game has Started
I am currently making a game with the java library LibGDX and want to add XBox 360 controller support using the GDX-Controllers extension. At the moment I have a setup where I create a listener to listen for particular button presses, then attach that listener to the static `Controllers` class using the method: `Controllers.addListener(myListener)`

This method works fine for listening for button press events from controllers which were connected *at the time the program started* but, if I try connecting a controller *after* the game has started, events for this controller are not registered.

I cannot see from the source code a way to *update* the listener for new controllers, and it appears from this blog post that disconnects and re-connects may not be supported on the desktop.

My question is: Is there a solution to my problem using GDX-controllers and, if not, what are my options for getting *full* Xbox 360 controller support (Including controller connects and disconnects) If I want functionality which integrates with the libGDX framework?

# Answer
Read the wiki!

Controllers connects/disconnects don't give listener events (right now), so controllers must be polled manually.

The wiki says controller listeners don't work on the desktop for connects or disconnects. I'm no expert, I've just been reading the wiki in detail, but it looks to me like you must poll the controllers manually.

This code will give you the currently connected controllers:

```
for (Controller controller : Controllers.getControllers()) {
    Gdx.app.log(TAG, controller.getName());
}

```

Some refresh type functionality would also be needed to get updated lists.

Edit: Based on the way the source is written, controllers are only detected when the control classes are loaded.
> 4 votes

---
Tags: java, libgdx, input, controllers, xbox-controller
---


title: How to use LWJGL Vertex Buffer Objects?

text:
# Question
Title: How to use LWJGL Vertex Buffer Objects?
I have been learning how to make a game with LWJGL for a while now by following YouTube tutorials online but I've recently been having a problem understanding Vertex Buffer Objects. I've looked at several tutorials including the one at the LWJGL Wiki, but I still don't understand how to use them.

Can someone please clarify how Vertex Buffer Objects should be used? I understand the code behind it but I don't know how it should be used. I know that the VBO should only be created once and be rendered every frame/loop. But my main question is, is there one Vertex Buffer Object per game or one per Object to be drawn? Also, what's the difference between VBOs and Interleaved VBOs?

# Answer
## Interleaved VBOs

Let's assume you have vertices V\_1, V\_2, ... V\_i each having position *p* and normal *n*. Positions and normals are called vertex attributes. Vertex attributes can be stored in an array, e.g. `positions = {p_1, p_2, ..., p_i}` and `normals = {n_1, n_2, ..., n_i}`. If you feed these arrays to OpenGL, you are using non-interleaved VBOs. You can also combine them to a single array as `attributes = {p_1, p_2, ..., p_i, n_1, n_2, ..., n_i}` and tell OpenGL the offset in the array where each attribute starts.

Alternatively, if you store them as `attributes = {p_1, n_1, p_2, n_2, ..., p_i, n_i}`, you are using interleaved VBOs. In this case you again feed a single array to OpenGL, tell where the first element of each attribute starts, and how many elements to skip to find the next element of the same attribute type.

See this answer about the benefits and downsides of interleaved VBOs. For performance reasons I would recommend to implement only interleaved VBOs from the beginning, unless it is considerably easier for your data to be used with non-interleaved VBOs.

## Sharing VBOs

Every time you change a binding (e.g. current VBO) in OpenGL requires some processing. Usually you want to avoid unnecessary bindings if you want to maximize performance. It's possible to have a unique VBO per object or combine all of the meshes in a single VBO. I can't say which is usually better approach, but I would say a unique VBO per mesh is at least easier to implement and I would recommend that as your first implementation. Combining multiple meshes in a single VBO can become ugly when the meshes have different attributes, e.g. one mesh having positions and normals and other one having positions and texture coordinates. Also in OpenGL ES you can quickly reach the limitation of 65536 vertices per VBO, as the indices in index buffer are 16 bit.

See this answer for a better breakdown.
> 1 votes

---
Tags: opengl, java, lwjgl, vertex-buffer
---


# Question
Title: Self occluding object and alpha blending
Look at the object I've rendered with my app:

It's the same screen twice, above the original and below I've drawn (by hand :P) the shape of the mesh of one of plant's leaves. You can clearly see where the problem is.

From what I understand, this leave is drawn **before** the other leaves, writing a higher value to the depth buffer but not changing the pixel color (as it's transparent in that particular place). When the other leaves are drawn then their pixels in that place in the buffer are discarded since they're failing the depth test (they're farther away from the camera).

Now while I understand what the problem is I don't know how to solve it. This whole plant is one object so I can't sort by depth. What should I do?

# Answer
While there is some interesting research into order-independent transparency rendering, it's extremely complex to implement. And even sorting individual leaves can still cause artifacts where one leaf overlaps itself. So your safest bet is probably **Alpha Testing**.

This is where you specify a threshold opacity value; anything above that value is rendered 100% opaque (and writes to the depth buffer), and anything below is not rendered at all (and does not write to the depth buffer - ensuring that other, occluded geometry can still be rendered there later).

Older graphics pipelines had a dedicated alpha testing phase for this. Newer ones often just use the discard command under the hood.

The trouble with this is that instead of soft translucent falloff, Alpha Testing gives you **sharp aliased edges**.

If your texture is relatively crisp-edged and you're usually a long distance from these surfaces, or you're using a post-process antialiasing filter anyway, then these jaggies should not look any worse than typical geometry silhouettes. You can probably stop here.

But if you can get close to the texture or your alpha falloff is very feathery, you'll often see jagged step artifacts.

(Images excerpted from the Wolfire Games Blog. These show the artifacts better than the Unity docs image I was using earlier. Note the fringes in the top-left, incorrect sorting top-right, and aliased edges bottom-left. In the bottom-right, the foreground leaves still show aliasing where they overlap the trunk, but the texture detail makes this less noticeable than aliasing against the sky.)

One way to address these is to use a **hybrid 2-pass shader**. The first pass renders with alpha testing, to ensure proper z-sorting of the opaque portions. The second pass renders with alpha blending enabled and depth writes disabled, to fill-in the translucent fringes without creating the cutouts you see in the image in the original question, where depth writes from one leaf prevent the others from rendering fully.

The fringes can still visually intersect each other in incorrect ways due to the lack of sorting, but in practice this is often not very noticeable, especially in areas of high texture detail or similar colours overlapping.

A hat tip is due here to the awesome devs at Asteroid Base who introduced me to this hybrid strategy, used to great effect in rendering the enemy characters in Lovers in a Dangerous Spacetime.
> 10 votes

---
Tags: rendering, depth-buffer, alpha-blending, occlusion
---


# Question
Title: What kind of physics to choose for our arcade 3D MMO?
We're creating an action MMO using Three.js (WebGL) with an arcadish feel, and implementing physics for it has been a pain in the butt.

Our game has a terrain where the character will walk on, and in the future 3D objects (a house, a tree, etc) that will have collisions. In terms of complexity, the physics engine should be like World of Warcraft. We don't need friction, bouncing behaviour or anything more complex like joints, etc. Just gravity.

I have managed to implement terrain physics so far by casting a ray downwards, but it does not take into account possible 3D objects. Note that these 3D objects need to have convex collisions, so our artists create a 3D house and the player can walk inside but can't walk through the walls.

**How do I implement proper collision detection with 3D objects like in World of Warcraft?** Do I need an advanced physics engine? I read about Physijs which looks cool, but I fear that it may be overkill to implement that for our game.

Also, how does WoW do it? Do they have a separate raycasting system for the terrain? Or do they treat the terrain like any other convex mesh?

A screenshot of our game so far:

# Answer
> 1 votes
You will likely need some kind of polygon collision detection and reaction. Also, you will need a way to organise it, like in a BSP tree or octree, as a lot of 3D objects will need to be culled when checking for collision or rendering to keep performance.

If this is the way you are going it is going to take a long time, not just to do but to learn if you don't know what you are doing already. The benefits are rewarding but much easier is to use an engine that has all this stuff in it already. Then you just have to learn how to use it.

Goodluck using javascript.

# Answer
> 3 votes
You stated that it will be a MMO game - don't do this kind of stuff client-side. You will have problems with cheaters, because it's fairly easy to modify your code so they can fly/no-clip etc.

If your terrain is heightmap-based just prepare your world so you have all of the objects inserted (houses, trees etc.) and generate some kind of mask which will exclude non-walkable places on the map. Take a look a this example for how it should look like:

Then on the server-side just check if the user is not on one of the red spots, if so just move them away (or stop movement when they are about to enter one).

To generate such mask you should loop through all of your objects and get their intersections with terrain (for example raycast from every vertex below some height). At least that's how I'm doing it and it works perfectly.

Of course that will work only if your terrain is heightmap-based, so no overhangs, caves etc (you would have to modify it a bit to get it working on multiple heights).

---
Tags: collision-detection, webgl
---


# Question
Title: Should game logic update per second or per frame?
I'm trying to wrap my head around how and when to update an entities position.

My game loop updates logic at 25 FPS and renders at 50-60 (Depending on the computer hardware).

So lets say I'm moving an object from 0 to 75 over a course of 100ms. In my update logic, should I update the position based on a per frame value or a per second value?

I was doing the math, and came up with and interesting find.

Since the update function updates at a rate of 25 fps, this means that it will be called at 40ms, 80ms and 120ms.

And the render function updates faster at a rate of 60 fps (for the sake of argument), which means it will be called at 16, 32, 48, 64, 80, 96, and 112ms

So if you line up all of these events on a timeline you'll notice that at the 6th render (96ms) the value of our position would be 72. And on the 7th render, the position would be 75.

Then the update function would be called at 120ms and would notice that the value is 75, but the current time is 20ms over what it should be.

Now I know that 20ms isn't much, but how do you compensate in collisions, physics, and AI for this? Should I instead update my values per frame instead of per millisecond?

# Answer
> 6 votes
I had to address this same problem, basically you're doing it the right way, updating at a set rate of updates per second, and thus a set speed per second and rendering as fast as possible independently of that speed.

That way it doesn't matter how you measure things in your update as long as you keep it consistent it'll be the same speed regardless of how fast the hardware draws things.

What you need is a way of interpolating between updates each time you do a render, since your display is updating regularly but your logic isn't.

If I may, here's some pseudo code:

For the sake of example, lets say these numbers are integers & now() returns the current time in milliseconds.

```
// Initial values
updatesPerSec = 25;               // How many updates you do per second.
skipTicks = 1000/updatesPerSec;   // The number of milliseconds between updates.
nextUpdate = now();               // When next update should occur.
currentTime = now();              // The current time.

// Game loop
while(running) {

    // Update current time
    currentTime = now();

    // While we are behind in updates, do updates! Keep doing them till we catch up.
    while(nextUpdate < currentTime) {
        update();
        nextUpdate += skipTicks;
    }

    // Calculate how far in between updates we are:
    // Near 0.0 values: update just occurred.
    // Near 1.0 values: update about to happen.
    // Read this equation till it makes sense what's happening here:
    interpolation = (currTime + skipTicks - nextUpdate) / skipTicks;
    render(interpolation);
}

update() {
    // update game logic & physics here
}

render(interpolation) {
    // Draw objects using the interpolation value.
    // Interpolate animations using this value, for eg: if you know an
    // object's velocity, predict it's future position and draw the object where
    // it will be in a moment's time to reduce animation 'stutter'.
}

```

That's actually the basic loop I use in almost anything, I can't remember where I found it but full credit to the original creator, it's served me well and keeps things incredibly simple that way.

But it does mean you need a way of actually using the interpolation value. That means for objects that are moving you need to have a sense of what direction and what speed to interpolate the value. With updates of velocity 25 times a second, the simple interpolation will achieve the appearance of logic updates every frame without actually calculating them.

Hopefully that helps!

---
Tags: javascript, html5, game-loop
---


# Question
Title: How do I avoid pathfinding characters getting stuck in corners?
I used A\* pathfinding to return a list of Tiles to get from an enemy to the player. After that, I wasn't sure how to actually move the enemy.

What I ended up doing was get the first Tile in the path. Then, check all 8 directions from the enemy's current tile. If the path tile is in the enemy tile's adjacent bottom square, move like this. If it's the right square, do that, etc. When the tile of the enemy is the same as that tile in the path, remove it from the path, and repeat for the next one.

This works, except my character sometimes gets caught around corners. This is because it thinks it should be moving horizontally (the next tile in the path is above it) when it's actually more of a diagonal movement to actually get to it.

I need to know two things:

1. Is there a better way I should do the movement after calculating the tiles in the path?
2. What are some ways to deal with the corners and diagonals? I was thinking perhaps some sort of random movement, but it's kind of janky. In the end, don't care how silly it is as long as the enemy doesn't get stuck!

Really new to all of this, so would appreciate some advice!

# Answer
> 15 votes
# Scenario

It seems your pathfinding and collision detection have different ideas of what's OK, when it comes to walking around corners.

Say your pathfinding plans out this path (brown squares are walls, yellows are empty space, green is an enemy character, arrows are the planned path):

The enemy character then moves directly toward each point from the previous one, *expecting* to be able to do this

...but hits a wall here.

Now, what does your collision resolution code do?

I suspect based on your video, that when the enemy hits a wall, they're just sent back to the direction they came from. (Or the enemy doesn't try to move there in the first place. Same idea.) This means the same thing happens again next frame.

...hence why cornering enemies get stuck.

# Quick solutions

Both your collision resolution and your pathfinding methods make *valid* but *different* assumptions about corners.

You could either **change your pathfinding** to not cut corners

or **change your collision detection**, perhaps to Separating Axis Theorem, so the enemy is popped out by the smallest possible displacement.

Fancier solutions I've seen games use include special collision detection logic for corners, considering characters' sizes in the waypoint graph and smoothing calculated paths' motion. (This question might also be handy.)

---
Tags: xna, algorithm, path-finding, collision-resolution
---


# Question
Title: Correct GL settings to mix 2D and 3D rendering
I'm programming a 3D game engine with 2D GUI. The GUI objects have partially transparent textures and the transparency works more or less. The sky color is rendered in transparent areas of the textures but the 3D objects aren't.

This is my initialization code:

```
private static void initializeOpenGL() {

    //Enabling OpenGL functions
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
    glEnable(GL_BLEND);

    //Using them
    glCullFace(GL_BACK);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

}

```

And this is my code to switch from 2D to 3D and vice versa. I am confident it is being run at the correct time.

```
public static void switchTo2D() {

    if (currentRenderDimension != Dimension.DIM_2) {

        glMatrixMode(GL_MODELVIEW);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        gluOrtho2D(0, Display.getWidth(), Display.getHeight(), 0);
        glViewport(0, 0, Display.getWidth(), Display.getHeight());
        glMatrixMode(GL_MODELVIEW);

        glPushMatrix();
        glLoadIdentity();

        currentRenderDimension = Dimension.DIM_2;

    }
}

public static void switchTo3D() {

    if (currentRenderDimension != Dimension.DIM_3) {

        glPopMatrix(); //From 2D
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        gluPerspective(PreferenceHelper.getInteger("fieldOfView"), (float) Display.getWidth() / Display.getHeight(), 0.1f, 1000);
        glViewport(0, 0, Display.getWidth(), Display.getHeight());
        glMatrixMode(GL_MODELVIEW);

        currentRenderDimension = Dimension.DIM_3;
    }
}

```

I believe it should correctly switch the settings, but clearly it does not:

I have verified that the .png textures ARE transparent.

# Answer
The code you are using to switch between 2D and 3D seems OK. Your problem should be on the GL states. Usually, when rendering sprites and 2D GUI, I use the following states:

```
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);

```

Then when switching back to 3D, I normally set:

```
glCullFace(GL_BACK);
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glDisable(GL_BLEND);

```
> 1 votes

---
Tags: opengl, textures, rendering, lwjgl, transparency
---