# Question
Title: How do I make a 2D character aim their gun toward the mouse?
Heli Attack is a perfect example of the shooting mechanic I'd like. The character aims perpetually toward the mouse. What's going on here?

From what I've read so far, you could separate the arm and rotate that. I've also noticed some people use a different sprite for each weapon.

How can I achieve this?

# Answer
> 12 votes
I'll answer with an autobiography.

# Projector sheets

You know those ancient projectors that come with transparent sheets? In primary school, I discovered you could draw a character's torso on one transparent sheet...

... and then take out another sheet, lay it on top, and draw arm with a gun on it ...

... and then rotate the top sheet with the arm on it (*reeeally carefully*, to keep the shoulder in the right place) ...

... and it would be amazing. I made multiple characters had them fight.

# Draw order

In secondary school, I taught myself Game Maker and I was making a platformer game. Playing around with sprites, I remembered my childish projector sheet battles and thought *I wonder if I could do that with code*.

So I drew sprites like I'd drawn them years ago and wrote code in the player's Draw event, something like

```
var rotation = direction_to_point(self.shoulder_position, mouse_position)
# Draw back arm
draw_sprite(player_back_arm, self.shoulder_position, rotation);
# Draw torso
draw_sprite(player_torso, self.position);
# Draw front arm
draw_sprite(player_front_arm, self.shoulder_position, rotation);

```

I remember I was really proud I had graduated to *two arms*. I printed the code out and taped it to the inside of my locker door, next to my circle-AABB collision resolution code. I figured this would get me girls. Hm.

When we did trigonometry in math class, I noticed that because the *tangent* of the *angle* between the adjacent and the hypotenuse equalled the length of the *opposite* over that of the *adjacent*, it was possible to find the angle given just the adjacent and opposite and that that's what the `angle_to_point` function in Game Maker must be doing.

Just imagine `A` is where the shoulder is and `B` is where you're aiming (the mouse position, say).

See my answer over here for a more complete explanation of the trigonometry involved, with sample code.

So that's how you might do that.

---
Tags: 2d, animation, sprites, side-scroller, aiming
---


# Question
Title: Jittery Rotational Movement with Arcball implementation
I have an assignment where I need to implement arcball using Opengl (~2.0). I have it more or less implemented but I have a some problems/issues/bugs and I'm not sure whats either causing them or how to solve.

Arcball rotation: Specically minor variance in mouse movement away from the axis I'm rotating on seems to "confuse" my program, causing artifacts (such as rotating briefly a completely different direction before resuming its current path).

Code:

```
void mouse_motion(int mx, int my)
{

    float angleRadians;
    //handles mouse motion events
    if ( arcball_on && (mx != last_mx || my != last_my) ) {
        // if left button is pressed
        lArcAngle = arcAngle;
        cout << " Last Angle: " << lArcAngle << endl;
        cur_mx = mx;
        cur_my = my;

        glm::vec3 va = get_arcball_vector(last_mx, last_my);
        glm::vec3 vb = get_arcball_vector(cur_mx, cur_my);
        angleRadians = acos(min(1.0f, glm::dot(va, vb)));
        arcAngle = ( ( angleRadians * 180 ) / 3.14159265 );
        cout << " Angle in degrees: " << arcAngle << endl;
        //cout << " ArcAngle after Mult: " << arcAngle << endl;
        arcAngle += lArcAngle;
        cout << " ArcAngle after accumulation: " << arcAngle << endl;
        axis_in_world_coord = glm::cross(va, vb);

        last_mx = cur_mx;
        last_my = cur_my;
        //glutPostRedisplay();

    }
// other code for other functionality...
}

void display()
{
    //Background color
    glClearColor(1, 1, 1, 0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    //glClear(GL_COLOR_BUFFER_BIT);
    glEnable(GL_DEPTH_TEST);

    // Matrix setup
    glMatrixMode(GL_PROJECTION);
    glViewport(0, 0, width, height);
    glLoadIdentity();
    gluPerspective(40, (float)width / (float)height, 0.1, 1000);

    // Matrix setup
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glTranslatef(0, 0, -3);

    int myFlagCtr = getFlagCtr();
    //cout << "CRX: " << crx << " CRY: " << cry << " CRZ: " << crz << endl;

    glPushMatrix();
        //glRotatef(arcAngle, axis_in_world_coord.x, axis_in_world_coord.y, axis_in_world_coord.z);
        glTranslatef(vec_blx, vec_bly, zScaling);
        glRotatef(arcAngle, axis_in_world_coord.x, axis_in_world_coord.y, axis_in_world_coord.z);

    if (myFlagCtr == 1) {
        // Set Wireframe
        glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
        // color red
        glColor3f(1.0f, 0.0f, 0.0f);
    }
    else if (myFlagCtr == 2) {
        glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
        // color red
        glColor3f(1.0f, 0.0f, 0.0f);
        glEnable(GL_POLYGON_OFFSET_LINE);
        glPolygonOffset(-1.0, -1.0);
        //draw object
        blDrawMouseMesh();
        glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
        // color red
        glColor3f(0.0f, 1.0f, 0.0f);
    }
    else if (myFlagCtr == 0 || myFlagCtr == -1) {
        // Bring back to Default
        glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
        glColor3f(0.53f, 0.12f, 0.47f);
    }
        blDrawMouseMesh();
    glPopMatrix();
    glutSwapBuffers();
}

```

As you can see between the two mouse vectors I get the angle between them, and the orthonogol vector which is the axis I am rotating around. But this only seems to work in a rather "dirty" and not particularly smooth way.

Edit: I now think the problem is the accumulation of degrees, when I switch axis's it remembers the angle from before, so it will "rotate" by the same amount previously plus the new angle, I'm not sure how to solve given the loading of the identity matrix causing non-accumulated values to reset.

# Answer
> 1 votes
You are using axis-angles to represent rotations, which is a bad idea, as you have discovered. You need to combine the rotations (i.e. compute the concatenation of one rotation by another), which is ugly to do with axis angle, and most certainly not what the code you posted does.

You should use quaternions, in particular use *shortest arc rotation*:

https://stackoverflow.com/questions/1171849/finding-quaternion-representing-the-rotation-from-one-vector-to-another

To find the quaternion that takes `va` to `vb`, and then multiply your view rotation quaternion by this delta one. So you code becomes:

```
glm::vec3 va = get_arcball_vector(last_mx, last_my);
glm::vec3 vb = get_arcball_vector(cur_mx, cur_my);
glm::gtc::quat shortest = shortest_arc_quaternion(va,vb);
quaternionRotation = shortest * quaternionRotation;

```

and later

```
glm::mat4x4 matrix = glm::gtc::mat4_cast(quaternionRotation);
glMultMatrixf(&(matrix[0][0]));

```

Quaternions can be turned into a matrix, which will replace `glRotatef()` by multiplying this matrix on top of the stack.

---
Tags: opengl, c++, rotation
---


# Question
Title: Moving rigidbody2d towards mouse click using AddForce
I cant get my rigidbody2d game object to move to where i click the mouse. The first click works. The object travels to the mouse click and stops. But the second time (or the third time) i click the object travels in som direction but its not quite correct and it never reaches the target! What am i not getting right?

```
   if (Input.GetMouseButtonDown (0)) {
             var mouseClick = Input.mousePosition;
             mouseClick.z = player.transform.position.z - Camera.main.transform.position.z;
             target = Camera.main.ScreenToWorldPoint (mouseClick);
             rotateToTarget = false;
             travelToTarget = true;
             print ("NEW TARGET: " + target);
             Debug.DrawLine (Camera.main.transform.position, target, Color.red, 10f);
      }

      if (rotateToTarget == false && travelToTarget == true) {

             var distanceToTarget = Vector3.Distance (player.transform.position, target);

             if (distanceToTarget > 2) {

                print ("Distance: " + distanceToTarget);

                target.z = 0;

            player.rigidbody2D.AddForce (target * travelSpeed);

             } else {

                travelToTarget = false;
                print ("travelling COMPLETE");
             }
      }

```

# Answer
> 2 votes
This is the error:

```
player.rigidbody2D.AddForce (target * travelSpeed);

```

You are ignoring the players current position, which is why it only works once because the initial position is (0,0,0).

Use `(target - player.transform.position) * travelSpeed` instead.

---
Tags: unity, physics
---


# Question
Title: Running two simultaneous animations on a model?
I am just looking for a broad answer to this question. I am more curious about the general information rather than the specific. Also, I tried to search for this, but I think it's hard to word it so you get the right question. Anyway:

One common thing I see in a lot of games is multiple animations on the same model.

i.e.

A character runs, but also raises his arms an shoots.

A character has a walking animation, but can also be carrying resources as he walks.

I am curious if the first model has a "run" animation and a "run while shooting" animation. Or if they have a "run" animation and a "shoot" animation and run them at the same time. Obviously the first is possible, but I am wondering how the second one is done.

Do they use two models for upper and lower body or is there a way to ignore certain parts of a model when animating?

I know this depends a lot on the model, the programmer, language and the way the animation is done.

But broadly, if you were making a model with the intent of it doing multiple animations at once, what would be the best way to go about it?

Again, not after detailed specifics, just an overview :)

Thanks!

# Answer
> 1 votes
> Do they use two models for upper and lower body or is there a way to ignore certain parts of a model when animating?

No and yes. No, only one model is used. Yes, there is a way to ignore certain parts of a model. Actually it is quite simple: You don't animate them. And when you have two animations that don't overlap in "parts affected" it is trivial to combine them (i.e. running them at the same time).

Technically the "ignore" part of the animation matrix is the identity matrix and multiplying both animation matrixes produces the desired combined animation.

---
Tags: animation, models, skeletal-animation
---


# Question
Title: How do I implement following behavior with a state-based AI?
I'm making a 2D game with two spaceships flying around shooting each other. One spaceship is controlled by the user, the by an AI. I want to use a simple Finite State Machine (FSM) for the AI.

I'm trying to make the AI ship follow the player's ship and stop at a given radius from it.

I've got a `GetInsidePlayersRadius` state, and a `StopMoving` state. But so far I got a weird bug involving the AI ship moving a few pixels, then stopping for a moment, than moving again, creating very fragmented movement.

The AI can move up, down, left, right, up-left, up-right, down-left, or down-right, just like the player.

What could create this fragmented movement behavior, generally when an AI agent is constantly trying to get inside a certain radius from an object, and stop when it's inside it?

How would you implement a following behavior of an AI as part of a Finite State Machine?

# Answer
> 1 votes
In my opinion it is perfectly fine to model the behavior with a FSM. Oftentimes we create inferior models with cluttered if-statements like suggested in the comments. But the FSM is not the problem.

To me it seems like you are experiencing jittering movement because your AI ship is always just at the border between "too far" and "close enough". Think about widening this border by using too different radii. One for getting a bit closer than absolutely necessary (r1=50m) and one for "oh I'm no longer close enough" (r2=80m). Where r1 \< r2 and r2 = your original radius.

Go to state `StopMoving` once you are within r1 and only go back to `GetInsidePlayersRadius` when you are within r2 no longer. In the meantime fire at the player and dodge bullets.

---
Tags: ai, movement, fsm, steering-behaviors
---


# Question
Title: How to draw or translate into world space?
I've been hacking around with OpenGL, but there's a few concepts which I can not find the answer on.

I want to draw three GL\_QUADS next to eachoter like so: \[2\]\[3\]

I know GL\_QUADS are deprecated, but for this question i'd like to use them nonetheless. Each quad will have its own color, the first being red, second green and the third blue. \[r\]\[g\]\[b\]

my code:

```
void display()
{
  glClear(GL_COLOR_BUFFER_BIT);

  GLfloat vertices[] = {
    -1, -1,  1, -1,  1, 1,  -1, 1,
     1, -1,  3, -1,  3, 1,   1, 1,
     3, -1,  5, -1,  5, 1,   3, 1
   };

   GLfloat colors[] = {
    1, 0, 0,  1, 0, 0,  1, 0, 0,  1, 0, 0,
    0, 1, 0,  0, 1, 0,  0, 1, 0,  0, 1, 0,
    0, 0, 1,  0, 0, 1,  0, 0, 1,  0, 0, 1
  };

  glLoadIdentity();
  glEnableClientState(GL_VERTEX_ARRAY);
  glEnableClientState(GL_COLOR_ARRAY);

  glVertexPointer(2, GL_FLOAT, 0, vertices);
  glColorPointer(3, GL_FLOAT, 0, colors);

  glMatrixMode(GL_PROJECTION);
  glTranslatef(-1, 0, 0);

  glDrawArrays(GL_QUADS, 0, 12);

  glDisableClientState(GL_COLOR_ARRAY);
  glDisableClientState(GL_VERTEX_ARRAY);

  glFlush();
}

```

result being:

* I'm confused as which to which matrix I should apply the translation matrix and in which order.
* I'm almost certain I should not use glMatrixMode(GL\_PROJECTION)
* What are the initial values of a matrix?
* I'm not certain which coords to pass in the vertex array at this point, model space or world space?

I hope you can shed some light in my confusion.

# Answer
> 1 votes
> I'm confused as which to which matrix I should apply the translation matrix and in which order.

OpenGL mixes camera and model transformations which is highly unintuitive at first (GL\_MODELVIEW). Read the tutorials at the end on my answer to better understand things.

> I'm almost certain I should not use glMatrixMode(GL\_PROJECTION)

True. GL\_PROJECTION is for choosing between orthogonal (2D, UI) and perspective (3D) projection. Do not touch yet.

> What are the initial values of a matrix?

All zeroes but ones on the diagonal. Called identity matrix. Does nothing when multiplied on a vector or matrix. Use glLoadIdentity to reset matrices.

```
1 0 0
0 1 0
0 0 1

```

> I'm not certain which coords to pass in the vertex array at this point, model space or world space?

Model space!

See the ancient but still excellent NeHe tutorials for more info on these topics: http://nehe.gamedev.net/tutorial/lessons\_01\__05/22004/ , especially http://nehe.gamedev.net/tutorial/your\_first\_polygon/13002/

---
Tags: opengl, graphics-programming, c
---


title: Calculate The Proper X and Y Coordinate

text:
# Question
Title: Calculate The Proper X and Y Coordinate
I have a class called `Tile`, the constructor takes an integer that represents the tile's type. You can load a tileset ( via `loadTileset()` ) which initalizes the fields -

* tileset
* numOfTiles
* tileWidth
* tileHeight

My question is, in the constructor, depending on the type variable. How do I figure out the proper x and y cooridates to uses in the `getSubimage()` method.

So for example, if `type` is set to the value 2, I'd want to get the x and y position of the upper-left corner of number two.

```
import java.awt.image.*;
import java.awt.*;
import java.io.*;
import javax.imageio.ImageIO;

public class Tile {

private int type;
private BufferedImage tile;

// tileset attributes
public static BufferedImage tileset;
public static int numOfTiles;

public static int tileWidth;
public static int tileHeight;

// constructor
public Tile(int type) {

    // contruct tile
    this.type = type;
    // ...
    tile = tileset.getSubimage(0, 0, tileWidth, tileHeight);
}

public static void loadTileset(String filename, Dimension tileSize) {

    // load tileset
    try {
        tileset = ImageIO.read(new File(filename));
    }
    catch(Exception e) {
        e.printStackTrace();
    }

    // initalize attributes
    tileWidth  = (int) tileSize.getWidth ();
    tileHeight = (int) tileSize.getHeight();

    numOfTiles = (tileset.getWidth() / tileWidth) * (tileset.getHeight() / tileHeight);
}
}

```

# Answer
How about

```
int x = type % 3;
int y = type / 3;

```
> 1 votes

---
Tags: java
---


# Question
Title: Deferred contexts and inheriting state from the immediate context
I took my first stab at using deferred contexts in DirectX 11 today. Basically, I created my deferred context using `CreateDeferredContext()` and then drew a simple triangle strip with it.

Early on in my test application, I call `OMSetRenderTargets()` on the immediate context in order to render to the swap chain's back buffer. Now, after having read the documentation on MSDN about deferred contexts, I assumed that calling `ExecuteCommandList()` on the immediate context would execute all of the deferred commands as "an extension" to the commands that had already been executed on the immediate context, i.e. the triangle strip I rendered in the deferred context would be rendered to the swap chain's back buffer.

That didn't seem to be the case, however. Instead, I had to manually pull out the immediate context's render target (using `OMGetRenderTargets()`) and then set it on the deferred context with `OMSetRenderTargets()`.

Am I doing something wrong or is that the way deferred contexts work?

# Answer
Turns out the answer was staring me in the face on MSDN: http://msdn.microsoft.com/en-us/library/windows/desktop/ff476424%28v=vs.85%29.aspx

> Immediate context state is cleared before and after a command list is executed. A command list has no concept of inheritance. Each call to FinishCommandList will record only the state set since any previous call to FinishCommandList.

I don't know why it's mentioned on the page for `ID3D11DeviceContext::FinishCommandList` when it's even more relevant for `ID3D11DeviceContext::ExecuteCommandList`.
> 1 votes

# Answer
I think a good solution would be to record the state of the immediate context after the initialization code and then execute the list on each deferred context when you create it and then call FinishCommandList on the deferred contexts just to prevent the initialization operations from being merged into the actual command lists later on. But I'm not sure if that's what they intended.
> 0 votes

---
Tags: directx11, state, deferred-rendering
---


title: Should game objects draw themselves?

text:
# Question
Title: Should game objects draw themselves?
Assuming you have classes like `Player`, `Enemy`, `Map` and `Tile`.

The first approach to structuring rendering code would be to give each a `render()` method and let it draw itself:

```
void render(){
   player.draw();
   enemy.draw();
   // etc.
}

```

But considering the Model-View-Controller perspective, that feels wrong... Another idea would be to make a `Renderer` class, but then I wonder how you give the `Renderer` information what to draw.

Which one should I choose and why?

# Answer
> 4 votes
Let's boil this down to dependencies.

Now the first thing is first, *how* do you render something? Well the logical manner tells us that we need *some* asset which will be loaded and then displayed.

Assets:

* Sprite
* Sound
* Music

Now how to you get these assets into your program? You typically will have some sort of *Asset Manager* who's responsibility is to load them for you. Now you have a bunch of Sprites/Sounds/etc... who are owned by *who*?

Well the player is made up of several assets, and these assets are used exclusively by the player. It then makes sense to have the player directly manage its own assets. So you might have:

```
class Player
{
    Sprite _playerMain;
    Sprite _playerSword;
    Sound _aughghghghgh;
};

```

Now how do you draw these? You've already mentioned two possible approaches, both are good approaches.

**Let the player draw itself:** Each object in the game will have a `Draw();` function, and would call `Draw();` on each Sprite object it owns.

Pros:

* Used by half-life 2 and several other games
* Very simple to implement
* Fine control over render order

Cons:

* Plenty of duplicate code
* Unable to take advantage of batching or other rendering tricks
* Must pre-sort your sprite layers

**Use a rendering manager:** A rendering manager will typically have a render priority (layers), with each object assigned to a given layer. The manager then batches and renders sprites from layer to layer. Your sprites will essentially add/remove them to/from the rendering manager.

Pros:

* Separation of data and logic
* Sprite layering is built-in, no need to pre-sort
* Able to batch sprites efficiently
* Player, Enemy, and other objects no longer need to encapsulate rendering code

Cons:

* Additional infrastructure to write

Now each approach is just fine. My current project is almost a hybrid of the two due to special requirements. Now you aren't going to be writing a AAA game, so work with whichever approach you prefer.

# Answer
> 2 votes
It's a bad idea if you are talking about 3D / GPU rendering.

It's fine if you're rendering 2D / non-GPU, as it may make more sense to you organisationally.

The reason is that GPU rendering, for optimal (or even reasonable) performance, requires individual render *passes* that render groups of game objects with similar properties i.e. materials, since each material uses different shaders and sometimes, different textures... switching between different textures and shaders can cost considerable time on the GPU, hence this is best avoided.

Allowing each object to render itself (rather than being observed and rendered *by* a single monolithic renderer) breaks this grouping which would allow the GPU to perform optimally. Some game objects can consist of multiple different materials, which would also break this grouping.

Even so, for small numbers of objects and low-cost shaders, this doesn't really matter much running on modern GPUs. But as soon as you have complex materials and many game objects, it is a far better idea to render from a single class / function, by inspecting game object properties.

---
Tags: java, 2d, rendering, design-patterns, mvc
---


# Question
Title: How do I calculate rotation caused by bounce friction?
Following on from my previous question: I have the ball quite realistically bouncing from surfaces it hits. Now I'd like to make it **spin from the friction of the hit**.

Showing this is simple enough: I rotate the ball by its angular velocity every tick and apply the same rotation when it's rendered.

When a ball hits a wall, I know that the speed of rotation is affected by...

* the ball's *initial speed* when hitting the surface
* the *friction coefficients* of the ball and surface (physical constants)
* the *angle of incidence* (the angle between the ball's incoming velocity vector and the surface normal).

The angle of incidence is approximated by the dot product of the ball's impact and exit velocity vectors. (1 meaning high spin, -1 meaning no spin, and everything else relatively in between)

Multiplying all of the above together and making sure they were then transformed to the range 0 - 1, and multiplied by max rotation speed, the ball seemed to respond in rotation speed as expected. Except for one thing: It would always rotate clock-wise (because of positive values).

---

Is this a good method? Can you think of a simpler way?

If this method seems fine, what am I missing? How do I know when the ball should be rotating counter-clockwise?

# Answer
> 2 votes
Your method is nice, because it's very simple. One thing you might need is dependency on previous spin on the ball, which you do not take into account. The spinning ball represents rotational energy, so a realistic simulation would probably have to conserve it along with the other energies.

However, if the ball is not rotating upon impact, I can't imagine a situation in which it begins rotation against the direction of the incident angle. That is, "clockwise" or "counterclockwise" should be relative to whichever side of the normal the incident angle is.

I think simply multiplying the result by the original x-direction vector (+1 if traveling left to right, -1 if traveling right to left) should do it.

*Edit:* You can use the cross-product for this. `Incident cross normal` provides a vector in the Z direction only (if we are on the 2D x-y plane). Look at the z-element: if it is positive, the ball's approach should cause it to spin clockwise. If it is negative, the ball should spin counterclockwise.

# Answer
> 3 votes
First get the surface tangent from the surface normal: **t** = (ny, -nx)

Then you can get the velocity component along the surface as **vt** = **v** dot **t**.

Now you can calculate the rotation of the ball: w = |(**normal** * r) cross **vt**|, where r is the radius of the ball.

Here I assume the ball has no rotational inertia and begins to spin instantly at the speed it would if it was to roll along the surface. You can use a coefficient of friction to make it more realistic and, if you want, take into account the rotational inertia of the ball.

# Answer
> 2 votes
Ókay, this might sound stupid but you're not using the dot-product of the ball vector and the surface normal and just doing an arccos to calculate the angle are you? Because then the angle would be positive whether it was positive (up to 90 degrees) or negative (ditto) as cosine is symmetrical around 0.
If this *is* the case then instead of using the normal of the plane, use the plane direction itself and subtract 90 degrees from the angle, so 0 to 180 would become -90 to +90 degrees (or -half PI to +half PI if you're radially inclined).

# Answer
> 0 votes
The first thing you need to adress is wheter the rotation speed or spin before hitting the wall; lets say Si; is greater, equal or lower than the value needed to maintain the same spin after hitting, say Ss. With this you can get the actual after hitting spin, say Se, using a friction value between the ball and the surface

Get the velocity component across the bouncing surface Vxi= Vi dot Vx, being Vx a parallel vector to the surface with magnitude 1.

The value you are looking is Ss= Vxi/r , this is to transform Vxi into angular speed. If Si is lower than Ss the ball should gain spin positively. If Si is equal to Ss the ball should keep aproximately the same spin, about this later. If Si is greater than Ss the ball should lose spin

the loses and gain of speed depend on the frictional value Fr. Actually it is a Cross between the radius and hte frictional force, but you can set that value as you wish.

You must also notice that besides the bounce coef, the ball loses some energy due to a friction between the ball and surface, thus Vxi is affected negatively. I would say bounce coef affects Vy and friction affects Vx.

You should take into account the deformation of the ball. This will affect the time or frames the ball is stick to the wall, thus the fritional force will exert for a longer time affecting spin and exit velocity. This deformation depende on how you want your model to be.

---
Tags: 2d, mathematics, physics, collision-resolution
---


# Question
Title: 2D to 3D perlin noise, I'm not sure I get it
I've been using 2d perlin noise to generate height maps for a little isometric terrain experiment. The noise value is directly related to the z-layer a tile will appear in: `Math.floor(noise * 10)`. Perlin is great but height is now always linear and I'm not sure how to change this.

One thing I tried was making the height value go up exponentially, producing a map akin to the image attached. Now my maintains are larger and more interesting looking, but this obviously produces gaps. I'm not sure how to "pad" or 3D-ify those layers. Any pointers?

```
    var diff = .04;
    var zz = Math.random() * 100;
    var x, y, xx, yy;

    for (var y = 0; y < maxY; y++) {
        this.grid[y] = new Array(maxX);
        for (var x = 0; x < maxX; x++) {
            xx = 0 + x * diff;
            yy = 0 + y * diff;

            this.grid[y][x] = Math.floor(Math.pow(simplex.noise(xx, yy, zz) * 4), 2.3));
        }
    }
    return this.grid;

```

**edit:** i'm sorry i'm not more clear. i'm not entirely sure what i'm asking because i'm not entirely understanding the maths. the terrain i've been trying to make starts at the base level with water. then some layers of grassy types, going into mountains. i'm not building minecraft here, i don't intend to dig around in it, but i would like to be able to rotate it sometime (replacing the tiles with cubes). right now, simplified, i'm expressing x and y as a 2d grid, with the value representing z, like so. z is really just my tile height.

```
var grid = [
    [1,1,1],
    [1,3,1],
    [1,1,1]
]

```

in this example i will draw 9 tiles, with the middle one at a height of 3 creating the gaps you see in the image. i was thinking the image would be more complete if this was a 3d grid.

```
var grid = [
    [
        [1,1,1],
        [1,1,1],
        [1,1,1],
    ],
    [
        [ , , ],
        [ ,2, ],
        [ , , ],
    ],
    [
        [ , , ],
        [ ,3, ],
        [ , , ],
    ]
]

```

blanks in this case will not be drawn. the values in the array could represent the type of tile for instance. i tried this with 3D noise but i'm very unsure how to interpret the density values (from -1 to 1). Drawing all density values under 0 (as the same tile) got me the image below which is cool, but not what i was hoping for. So far everything i've read about this does not explain what the values actually *mean*. translating the density values into into 'types' of terrain generates mostly nonsense, with random bits of water all over the place. the whole thing just looks like a giant cube with holes in it.

maybe i'm not making sense because what i want does not make sense, this is entirely possible. the internets is letting me down and i'm hoping some smart people can point me in the right direction.

# Answer
> 1 votes
Your tile positions are calculated according to your isometric transformation function.

If you want to "3d-ify" this, you will need to do the following:

Determine the screen positions of the four corner points of each tile. Since every corner point is bounded by four tiles, you need to take the heights of those four tiles, and average them to get the height / screen position of the corner point that they share. You can do this either before or after your isometric transformation; it makes little difference.

Now, per tile, get these four newly calculated corner points, and perform a fill between them (polygonal fill, most easily achieved as a scanline fill). You may get pixel gaps here and there. To avoid these use point-on-side-of-line detection while scanline-filling across the entire viewport. This way you will never miss a pixel.

Now all you need to do is make sure that you do this from back to front (painter's algorithm) and you should get what you want. This will, by the way, draw backfaces. Since your display is only 2D anyway, I wouldn't worry about that bit of overdraw. It likely won't be a showstopper.

**P.S.** In order for characters to move smoothly between tile centres, you would linearly interpolate (lerp) them from one tile-centre height to another.

---
Tags: html-canvas, terrain, perlin-noise
---


title: SSAO looks wrong

text:
# Question
Title: SSAO looks wrong
I'm trying to implement SSAO based on this tutorial. My setup:

* OpenGL 3.2
* Forward renderer
* View-space depth and normal in a single 16-bit floating point texture.

The result I get is this:

The black area follows the camera and is always in the center of the screen. This is my depth/normal pass shader:

```
#version 150 core
#extension GL_ARB_explicit_attrib_location : enable

uniform mat4 _ViewMatrix;
uniform mat4 _ViewProjectionMatrix;
uniform mat4 modelMatrix;

layout (location = 0) in vec4 aPosition;
layout (location = 2) in vec3 aNormal;

out vec4 vPosition;
out vec3 vNormal;

// Vertex shader.
void main()
{
    gl_Position = _ViewProjectionMatrix * modelMatrix * aPosition;

    mat4 modelViewMatrix = _ViewMatrix * modelMatrix;
    vPosition = modelViewMatrix * aPosition;
    vNormal = mat3( modelViewMatrix ) * aNormal;
}

// Fragment shader:
#version 150 core

in vec4 vPosition;
in vec3 vNormal;

out vec4 outDepthNormal;

void main()
{
    outDepthNormal = vec4( vPosition.z, normalize( vNormal ));
}

```

This is my SSAO shader:

```
// Vertex shader:
#version 150 core
#extension GL_ARB_explicit_attrib_location : enable

uniform float uTanHalfFov;
uniform float uAspectRatio;

layout (location = 0) in vec4 aPosition;
layout (location = 1) in vec2 aTexCoord;

out vec2 vTexCoord;
noperspective out vec3 vViewDir;

void main()
{
    gl_Position = aPosition;
    vTexCoord = aTexCoord;

    vViewDir = vec3( -aPosition.x * uTanHalfFov * uAspectRatio, -aPosition.y * uTanHalfFov, 1.0 );
}

// Fragment shader:
#version 150 core

uniform sampler2D depthNormalMap;
uniform sampler2D noiseMap;
uniform mat4 _ProjectionMatrix;
uniform int uKernelSize;
const int MAX_KERNEL_SIZE = 128;
uniform vec3 uKernelOffsets[ MAX_KERNEL_SIZE ];
uniform float uRadius;
uniform float uPower;

in vec2 vTexCoord;
noperspective in vec3 vViewDir;

out vec4 fragColor;

float ssao( in mat3 kernelBasis, in vec3 originPos, in float radius )
{
    float occlusion = 0.0;

    for (int i = 0; i < uKernelSize; ++i)
    {
        vec3 samplePos = kernelBasis * uKernelOffsets[i];
        samplePos = samplePos * radius + originPos;

        // project sample position:
        vec4 offset = _ProjectionMatrix * vec4( samplePos, 1.0 );
        offset.xy /= offset.w; // only need xy
        offset.xy = offset.xy * 0.5 + 0.5; // scale/bias to texcoords

        // get sample depth:
        float sampleDepth = texture( depthNormalMap, offset.xy ).r;

        float rangeCheck = smoothstep( 0.0, 1.0, radius / abs( originPos.z - sampleDepth ) );
        occlusion += rangeCheck * step( sampleDepth, samplePos.z );
    }

    occlusion = 1.0 - (occlusion / float( uKernelSize ));

    return pow( abs( occlusion ), uPower );
}

void main()
{
    vec2 noiseTexCoords = vec2( textureSize( depthNormalMap, 0 )) / vec2( textureSize( noiseMap, 0 ) );
    noiseTexCoords *= vTexCoord;

    // get view space origin:
    float originDepth = texture( depthNormalMap, vTexCoord ).r;
    vec3 originPos = normalize( vViewDir ) * originDepth;

    // get view space normal:
    vec3 normal = normalize( texture( depthNormalMap, vTexCoord ).gba );

    // construct kernel basis matrix:
    vec3 rvec = normalize( texture( noiseMap, noiseTexCoords ).rgb );
    vec3 tangent = normalize( rvec - normal * dot( rvec, normal ) );
    vec3 bitangent = cross( tangent, normal );
    mat3 kernelBasis = mat3( tangent, bitangent, normal );

    fragColor = vec4( ssao( kernelBasis, originPos, uRadius ) );
}

```

I guess something is going wrong with the depth reconstruction.

# Answer
Ok, I got it working. My depth writing shader now looks like this:

```
void main()
{
    float linearDepth = -vPosition.z * uLinearDepthConstant;
    outDepthNormal = vec4( linearDepth, normalize( vNormal ) );
}

```

And when I read it in SSAO shader, I inverted normals and multiply depth value with `(far - near)`.
> 3 votes

---
Tags: opengl, glsl, ssao
---


# Question
Title: How could I control an air hockey 's AI paddle?
I am making an air hockey game on Android with Box2D and libgdx. For the manual control, I just use the MouseJoint and it works perfectly. However, for the AI control, there is a problem:

I've made a method predicting the position of the puck in the near future (for example in the next 30 frames). Then I tried to move the paddle towards that predicted position such as: after exactly 30 frames, my paddle will arrive **in time** at **a specified point** near that position to hit the puck with **a specified velocity**.

But the problem is, if using MouseJoint, I can't specify the exact interval 30 frames. The paddle will arrive at the specified position, but it maybe sooner than 30 frames, or later than 30 frames. And I can't control the velocity when it arrive at that point either.

What I need here is a way to control my paddle to arrive at a specified point, with a specified velocity in a specified interval. Or is there any other way to control this AI paddle?

# Answer
> 1 votes
You have the time (30fps = 0.5seconds) You have the distance (DesiredPosition - Position).Length()

You can calculate your required speed now:

> Speed = Distance / Time;

Then just set this speed as your physic's objects velocity, and in theory it should reach the destination. This does not account for drag, friction, etc..

---
Tags: libgdx, box2d, ai
---


title: Proper Order to Process Each Frame

text:
# Question
Title: Proper Order to Process Each Frame
I'm writing a rudimentary 2D engine and am wondering what the proper or generally accepted order is for handling graphics, user input, sounds, and then other systems like physics.

If you have written an engine, please explain your order and why you picked that particular order.

# Answer
Typically, you'll go by logic wiht what needs first to be done for the subsequent steps.

1. **Input**
2. **Logic pre-physics** -- react to user input and prepare stuff for your...
3. **Physics simulation** -- Physics engine update here
4. **Logic post-physics** -- Stuff that needs to be done in reaction to the physics simulation, namely trigger reaction, graphics positioning w.r.t. physics, etc...
5. **Render/sound** -- they're the result of the current simulation frame.
> 2 votes

---
Tags: physics, graphics, sound, control
---


# Question
Title: How do I avoid A* pathfinding lists exploding?
I'm attempting to implement A\* pathfinding in my game, and it works for most of the iterations I've tested it with, but I've hit a few random cases where it never stops loading items into the Closed and Open lists, making me think I have a leak in my logic somewhere. I think it's caused when there are multiple options that have equal G+H values, and it even happens when the origin and target are only 2-3 steps apart, but I'm not sure how to protect against multiple equal values.

This implementation is based on the Wikipedia pseudocode and some other helpers I've found around the web:

```
private Point getNextPoint(Point sourceLoc, Point targetLoc)
{
    // clear the lists
    openList.Clear();
    closedList.Clear();
    // find direction of targetLoc
    GridFacing facing = findFacing(sourceLoc, targetLoc);
    // get starting adjacent locations
    foreach (Node node in getNeighbors(new Node(sourceLoc.X, sourceLoc.Y), (int)facing, targetLoc))
    {
        openList.Add(node);
    }

    Node previous = new Node();
    while (openList.Count > 0)
    {
        // current lowest G+H
        int indexS = openList.Min(f => f.F);
        // get next node with lowest G+H that is not the previous node
        Node node = openList.First(f => f.F == indexS && f != previous);
        // check for goal
        if (node.Loc == targetLoc)
        {
            return recurseNextNode(node).Loc;
        }
        // remove from openset
        openList.Remove(node);
        // add to closedset
        closedList.Add(node);
        // get neighbors of current location
        List<Node> sortedNeighbors = getNeighbors(node, (int)facing, targetLoc);
        foreach (Node neighbor in sortedNeighbors)
        {
            // not in closed set
            if (closedList.Contains(neighbor))
                continue;
            // steps from source
            int tempG = node.G + 1;
            // not already in openset or temp g less than existing g;
            if (!openList.Any(f => f.Loc == neighbor.Loc && f.G == tempG) || tempG < neighbor.G)
            {
                neighbor.Parent = node;
                neighbor.G = tempG;
                neighbor.H = Convert.ToInt32(GetDistance(neighbor.Loc, targetLoc));
                if (!openList.Contains(neighbor) && !closedList.Contains(neighbor))
                    openList.Add(neighbor);
            }
        }
        previous = node;
    }

    return new Point(0, 0);
}

```

What in this implementation is allowing for these massive loops, and how do I protect against it?

# Answer
> 1 votes
You have some serious performance issues, which could cause the behavior you're seeing in large graphs.

Here are some tips:

1. You don't need typically need a `closedList` in real-life - having a `HasBeenVisited` property on the `Node` will serve the equivalent purpose, but be much faster.
2. Your `openList` doesn't appear to be a priority queue, so operations like `Dequeue()` and `Contains()` will be O(n) rather than O(log n).

I've released a C# `PriorityQueue` implementation designed specifically for high-performance pathfinding. It does `Dequeue()` in O(log n) and `Contains()` in O(1).

---
Tags: c#, path-finding
---


# Question
Title: Fixed timestep with interpolation in AS3
I'm trying to implement Glenn Fiedler's popular fixed timestep system as documented here:

http://gafferongames.com/game-physics/fix-your-timestep/

In Flash. I'm fairly sure that I've got it set up correctly, along with state interpolation.

The result is that if my character is supposed to move at 6 pixels per frame, 35 frames per second = 210 pixels a second, it does exactly that, even if the framerate climbs or falls.

The problem is it looks awful. The movement is very stuttery and just doesn't look good.

I find that the amount of time in between ENTER\_FRAME events, which I'm adding on to my accumulator, averages out to 28.5ms (1000/35) just as it should, but individual frame times vary wildly, sometimes an ENTER\_FRAME event will come 16ms after the last, sometimes 42ms.

This means that at each graphical redraw the character graphic moves by a different amount, because a different amount of time has passed since the last draw. In theory it should look smooth, but it doesn't at all. In contrast, if I just use the ultra simple system of moving the character 6px every frame, it looks completely smooth, even with these large variances in frame times.

How can this be possible? I'm using getTimer() to measure these time differences, are they even reliable?

# Answer
> -1 votes
Check this out :https://stackoverflow.com/questions/20192775/box2d-frim-frame-rate-independent-movement/20283264#20283264 . Try using a filtered variable time step... if you can.

---
Tags: flash, actionscript-3, timestep
---


# Question
Title: Can I programmatically generate textures in java?
Is it possible to programmatically generate textures in Java, textures that could then be used to cover in game objects?

# Answer
> 7 votes
Well, technically speaking you can generate textures using any language. Even if you don't have any output on screen, as far as your language can represent integer/float (could get away with integers) and arrays, you are good to go.

The problem though is that not every texture could be generated procedurally. You usually need a formula as a stating point to represent that particular texture in order to generate it, then refine it based on some specific criteria. The formula could be anything like perlin noise, analytical shapes, complex numbers (fractals)..etc

There is even a book dedicated to this huge topic http://www.amazon.com/Texturing-Modeling-Third-Edition-Procedural/dp/1558608486

Extending the answer to include pros. and cons. of procudarally genrated textures:

Pros:

* You usually need less storage unlike traditional 1/2/3D textures which require huge storage.
* It's doesn't have a fixed size(resolution) like traditional textures, and hence can scale without losing quality.
* One basic procedural algorithm can be parametarized to generate different sets of textures.

Cons:

* Harder to make than non-procedural textures.
* They take more time to generate unlike non-procedural stored texture which only need to be read. (actually you can generate a texture once and store it, but you lose alot of the advantages).

---
Tags: java, android, textures, procedural-generation
---


# Question
Title: How to predict movement correctly when a player is invisible?
I have a multiplayer game and I'm doing client-side prediction, but some players can drink a potion and become invisible...

The problem is that when they become invisible I don't share anything that the client could use to know he's there, so when a player tries to step into a tile occupied by a invisible player, he predicts that he succeeds, and then gets a ugly position correction sent by the server.

One solution would be to share something so the client can tell, but then hackers could use it to find out where invisible players are, cheating.

Btw I already solved regular movement prediction, it works perfectly.

# Answer
This could be considered an animation problem. If a position correction comes back from the server due to an attempt to move into an invisible object, send back not only the correction but a flag indicating why the correction was needed. Instead of a player popping backwards, he may do a "woah" kind of reeling backwards animation, making it more believably look like he just ran into something.

In games using this approach, it's not uncommon to remove invisibility (at least momentarily) from anything that was run into. Among other things this gives incentive for invisible players to avoid crowds or getting too close to other characters, reducing the frequency that collision with an invisible player happens in the first place. Thus even if your animation for this kind of collision is weak (or non-existent), it's somewhat hidden by the invisible character popping into visibility and clearly telegraphing to everyone what just happened.

The animation need could be removed by not letting invisibility work at close range. This gives even more incentive to invisible players to avoid getting close to other characters. This is a common approach for stealth-based games and AI (replace "invisible" with "not visible to target") and can be seen in PvP games like World of Tanks. There's no need to worry about collision response with invisible characters if you nothing invisible is ever close enough to you to collide with (within latency limits).

Dracor's solution to just ignore collisions with invisible objects is also a good one. This does again require some animations (for the invisible players' client) so objects aren't just clipping through the player's avatar on his screen. If nothing else you can cause visible objects to always push invisible ones so that the invisible player is automatically moved out of the way on the server if someone collides with him.

Invisible-invisible collisions are a bit trickier. It may be advantageous to just disable collisions on them since nobody can see if two invisible objects are clipping together (assuming by "invisible" we mean that both objects aren't visible to the same client). If one of the objects becomes visible it automatically reverts to the visible-invisible collision response (push away the invisible object).

This all gets trickier if invisibility has complicated sets of who can see whom. The first or second solution above is likely best here if you need it. Not every problem like this needs a technical solution; many just need design solutions (e.g., don't allow this feature to your designers).
> 30 votes

# Answer
I really only see two options here if you don't want to tell the client where the invisible player is: 1) You ignore unit collision for invisible players - a simple solution, and players wouldn't be able to find the invisible players by collision tests either. 2) After deciding on the predicted path, you send the server the predicted path and correct the path itself on the server side, then send the new path back.
> 4 votes

# Answer
Unless I'm misunderstanding something, the solution is simple. Don't send the client information on all invisible players, only those who are within range that they could be subject to collision within the limits of motion during the interval that's being predicted. In other words, if the client is only having to predict 200 ms into the future, only send information on invisible players within `max_player_velocity units/sec * 1/5 sec` units away.
> 2 votes

---
Tags: multiplayer, client-server
---


# Question
Title: How can I "stick" objects to tables in Skyrim and still allow those objects to be player-interactable?
I'm trying to place a non-static pot (`RuinsPot01`) on a table (`RuinsAltar`) with the Havok simulation.

I place the pot a little bit above the table and turn on Havok. The pot falls down but is left floating slightly above the table.

If I turn of Havok and press `F` it is aligned correctly to the table, but as soon I turn on Havok Simulation, it jumps up slightly and floats as before.

Does any one have a fix for this? Making the pot static isn't an option, it has to be movable.

# Answer
This is a general answer for most 3d physincs engines, you can use one or both of this solutions:

1-) A solid object should have have the possibility of setting an inactive state, then the engine will not run any physic calculation for it until its first collision with any other object.

2-) Using proxy objects: The visible objects doesn't need to be the same that the physical object. You can use a proxy object scaled down a bit inside the visual object to fill the space between collisions.

That empty space between colliding objects is not a bug, is necessary for performance, when doing collision detection calculations. The engine should allow you to modify that value, if you set this value too small performance issues can arise and even wrong behavior like objects trespassing each other.

This answer is based experience using the same Havok engine in 3ds Max.
> 1 votes

---
Tags: havok, skyrim-modding
---


# Question
Title: How to draw a plane equivalent to a given btStaticPlaneShape using OpenGL
With all other shapes in bullet, you can easily get the transform from the `MotionState` which holds the origin, the scale, and the rotation. There seems to be no way to get the same information about a `btStaticPlaneShape`. How can I get this information, so that I can build a rectangle with 4 vertices that will act as a representation in OpenGL?

# Answer
Looks like btStaticPlaneShape is an infinite plane, so you could pick an arbitrary point and just draw a really big plane centered on that that point using the normal stored in btStaticPlaneshape
> 1 votes

---
Tags: opengl, c++, bullet-physics
---


# Question
Title: How can I port an XNA game to iOS and Android?
I made a little Windows Phone game with XNA and Farseer Physics engine and I want to port that game to iOS and Android. Is Monogame the only software that I can use or are there alternatives?

I don't want to change my entire code. It should be easy to port the game.

Is it possible to use Unity to port the game or is it better and easier to use other software?

# Answer
> 4 votes
MonoGame is a set of libraries for various platforms (such as iOS/Android) and tools that mostly re-implements the XNA interface. One of the most notable differences between MonoGame and .NET is the workflow around content projects.

Xamarin is a product which allows you to build iOS/Android apps in C# that run on Mono. You still require Xamarin to build an iOS/Android game that uses MonoGame. In this scenario, Xamarin lets you compile and deploy the game, but MonoGame is the library you're using.

Unity3D would require you to re-architect your game. You could re-use graphical and sound assets, and even large portions of code, but it would be more of a "rewrite" than a "port", so it would most likely take significantly longer. (Note that you do not require Xamarin to create an iOS/Android game in Unity3D.)

# Answer
> 1 votes
The only alternative to MonoGame, as far as I am aware, is **ExEn**, which is a library I made. It's missing several XNA features (it only works for `SpriteBatch` games). The code quality is widely considered to be superior to MonoGame's (although it has been a while since I have looked myself).

MonoGame, I think, gives a lot more guidance to beginners. ExEn expects you to be a competent coder and not afraid to read source code (especially the samples).

I have no idea whether ExEn will still work unmodified. The have been lots of iOS and Mono updates, and **I have not updated ExEn for a *long* time**.

Both ExEn and MonoGame require Xamarin's Mono for iOS / Mono for Android as the underlying platform.

Basically MonoGame and ExEn each provide an implementation of XNA. While Mono provides an implementation of .NET.

Unity requires you port from XNA to its own API.

# Answer
> 0 votes
IIRC, it is the either Monogame or Xamarin. Xamarin costs a lot more, but I can definitely say it is worth the money, depends on your financial position as well. MonoGame is okay, but I have heard of a lot of porting issues regarding this method. Good Luck!!

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


title: Thick Ray interaction with AABB

text:
# Question
Title: Thick Ray interaction with AABB
I would like to intersect a thick ray (actually a cylinder) with an AABB. The current code to perform intersection with the ray is the following.

```
template <class RealT>
bool CAABB<RealT>::Pick(const CPoint3T & base, const CVector3T & dir) const
{
    // SLAB based optimized ray/AABB intersection routine
    // Idea taken from http://ompf.org/ray/

    RealT l1 = (_minPnt.x - base.x) / dir.x;
    RealT l2 = (_maxPnt.x - base.x) / dir.x;
    RealT lmin = minT( l1, l2 );
    RealT lmax = maxT( l1, l2 );

    l1 = (_minPnt.y - base.y) / dir.y;
    l2 = (_maxPnt.y - base.y) / dir.y;
    lmin = maxT( minT( l1, l2 ), lmin );
    lmax = minT( maxT( l1, l2 ), lmax );

    l1 = (_minPnt.z - base.z) / dir.z;
    l2 = (_maxPnt.z - base.z) / dir.z;
    lmin = maxT( minT( l1, l2 ), lmin );
    lmax = minT( maxT( l1, l2 ), lmax );

    if( (lmax >= 0.0f) & (lmax >= lmin) )
    {
        // Consider length
        const CVector3T rayDest = base + dir;
        CPoint3T rayMins( minT( rayDest.x, base.x), minT( rayDest.y, base.y ), minT( rayDest.z, base.z ) );
        CPoint3T rayMaxs( maxT( rayDest.x, base.x), maxT( rayDest.y, base.y ), maxT( rayDest.z, base.z ) );
        return
            (rayMins.x < _maxPnt.x) && (rayMaxs.x > _minPnt.x) &&
            (rayMins.y < _maxPnt.y) && (rayMaxs.y > _minPnt.y) &&
            (rayMins.z < _maxPnt.z) && (rayMaxs.z > _minPnt.z);
    }
    else
        return false;
}

```

I would like to write a routine that takes an additional parameter for ray\_thickness (diameter of the cylinder) and compute the intersection.

# Answer
I see 2 naive approaches, I don't know which one is faster:

1. You could project the AABB on the plan which is orthonormal to the direction of the ray, then resolve the problem of intersection of a 2D sphere with the projected AABB.
2. You could project your cylinder on each of the 3 axis and check for intersection with the 2D rectangle (which is the projection of the AABB), then combine the 3 results to decide on the 3D intersection.
> 1 votes

# Answer
I think you'd find that doing several ray checks would be faster and conceptually simpler than checking several manifolds against each other. They call these *ray packets* in raytracing literature.

I'd suggest using 6 rays for the cylinder's radius, and one for the centre, totalling 7. You could even get away with as few as 4 or 5 rays, depending on how you want approximate the cylinder shape. This will be fast for non-axis-aligned objects, and can be blisteringly fast for AABBs. Provided the distance between each ray in the packet is small enough (slightly smaller than the diameter of your smallest detectable entity), you'd never miss anything. Here's a picture of a 7-ray cylinder end-on:

```
       o
 o           o
       o
 o           o
       o

```

I'd go so far as to say this is the more common approach in games due to cost.
> 0 votes

---
Tags: c++, raycasting, intersection, aabb
---


title: Random movement of enemy

text:
# Question
Title: Random movement of enemy
I am making a game in XNA, and I am trying to make an enemy move randomly.The game is a platform game, so the enemy only moves left and right.I want it to move right or left a little, then stop.I didn't know how to update and code it.

This is my file...My file!

# Answer
> 1 votes
A common approach is too use two variables in your enemy class.

```
int time = 0;       // This represents the time since the last instruction
bool left = false;  // This represents the direction the enemy is going

```

You will then want to have a method that runs every x amount of time and has a random change of moving the enemy in a specific direction or stopping him.

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


# Question
Title: How can I render from a buffer that exists and was created on on the GPU?
I'm looking for a unity API or function call to allow me to do the following ...

I wrote some really complex functions that are compute shaders. These compute shaders manage a huge compute buffer containing voxel information. I then take portions of (or the entire) voxel buffer in another compute shader and produce a vertex buffer. All of this is done on the GPU with only compute shader calls from the CPU.

Now I want to render that vertex buffer but I must be looking in the wrong place because I can't find any information on how this is done within unity despite there being other examples on how to do this using raw DX or openGL approaches.

Can anyone point me in the right direction to determine how I can render using a specified shader a buffer already in graphics RAM (and ideally give it some textures too)?

# Answer
> 2 votes
Unity has 2 static functions on the graphics class to allow you to do this. It does however avoid the CPU altogether (desired result)

```
void OnRenderImage()
{
   Graphics.DrawProcedural()
   Grpahics.DrawProceduralIndirect()
}

```

# Answer
> 0 votes
Sounds like you want to Render to a Texture.
After you do a render pass to that texture using your shaders, you can attach that texture to a quad and render it with the main camera.

# Answer
> 0 votes
If you have vertex and triangle data in your buffer you can use :

```
Buffer.GetData()

```

to get back those infos in Vertex and triangle arrays, then with Graphics.GL library, rebuild a mesh and actualise the normals and assign any material you want.

Well only in the case that your buffer is Read Write enabled.

EDIT :

It's not only Unity which prevents you to use data directly from the GPU Buffers by the CPU, it is the whole principle of Accelerated graphics. That said you should be able to read data in your compute shader Try to see on the side of registers, if you can specify a registeer for your buffer (which you can) you have probably a way of reading from this register in a classic shader?

---
Tags: unity, rendering, vertex-buffer
---


title: Do I need threads in Hangman game?

text:
# Question
Title: Do I need threads in Hangman game?
I wish to implement a simple multiplayer Hangman game with the rule slightly bended.

Rule: All the players have to guess the alphabets in the word at the same time. Whoever player guesses a correct alphabet gets a point, and the player who puts the ending alphabet gets bonus points. This will be about speed. The faster correct guess gets you ahead of others.

I intend to have a Qt/QML based GUI and the programming language will be C++. Platform will be Linux.

***I am thinking I'll need:
\- One thread for handling user typing.
\- Second thread for parallel display of what other players are typing.
\- Third thread for parallel display of scores of every player on every player's screen.***

Do I need these 3 threads or I am barking the wrong tree?

# Answer
> 1 votes
When you can avoid threading, you should do so. Threading makes an application magnitudes more complex to develop, test and maintain. Any data exchange between threads can either lead to deadlocks or to race conditions which result in obscure and impossible to reproduce bugs.

There are APIs which make threading more manageable, like critical sections, mutexes or channel-based information exchange, but these present some pitfalls in themself and can be easily forgotten in situations where they should be used.

The only *good* reason to use threading is usually to parallelize very CPU-intense calculations. But not every problem can be parallelized easily. So even in that case you should t(h)read lightly and minimize any communication between threads.

# Answer
> 0 votes
Nowhere. No part of this game requires computations hard enough to justify the cost of maintaining multiple threads.

---
Tags: c++, multiplayer, multithreading, linux
---


title: Opengl Compute Shaders support?

text:
# Question
Title: Opengl Compute Shaders support?
I have a question about compute shaders.

My GPU is an AMD mobility Radeon 6490 which as the AMD website says supports OpenGL 4.1. However, when I check for my compatibility version via 'glGetString(GL\_VERSION)' I get 4.3.12618 Compatibility Profile Context 13.250.18.0. Does that mean I should be able to use compute shaders as they are introduced in OpenGL 4.3?

If I try to create a compute shader in my program GLenum type GL\_COMPUTE\_SHADER is unknown but I'm not sure if newest headers are included.

My GPU also supports the 'GL\_ARB\_compute\_shader' extension.

So is there a special way to enable this extension or should I try to somehow include newer headers? Or will I not be able to use compute shaders at all (I don't want to use OpenCL)?

Thanks for answer.

# Answer
Your guess is correct - you need newer headers.

A bit of explanation:

If you use Windows, you don't get new API 'out of the box'. Headers provided with Windows SDK and SDK included in Visual Studio has only standard GL.h, containing only functions present in MS generic implementation (oooold).

Basically, when you create apps using OpenGL, you need to download the newest header from OpenGL site and then query adresses of required functions directly from DLL that contains OpenGL implementation - wglGetProcAddress(). The reason for that, is because GL implementation is provided by GPU vendors and updated automatically when GPU drivers are being installed - that's also the reason, why GPU drivers updating is so important when it comes to OpenGL.

But it's a mess. And that's why various libraries were developed, that allows you to make it in more automated way. The best and most-widely used example is GLEW.

You already use it, so you probably know some of the above.

Now, the problem is probably with version of GLEW you're using now - it simply doesn't define some constants, so you are not able to use them. If I remeber correctly, support for compute shaders was added in version 1.7.0. It IS supported by now, beacause I use it in my project.

Simply go to download page of GLEW and get the newest version. Replace current headers, so new features will be visible.

Also, don't forget to replace .lib files and copy DLL's to Bin folder of your project or system32/SysWOW64 directory. GLEW has recently merged x86 and x64 versions, so both are now in single package.
> 3 votes

---
Tags: opengl
---


# Question
Title: What interface should be responsible for specifying the initial position of a game object?
I'm making a simple Pong clone game and have been having an issue deciding on how my classes should handle the initial placement of an object.

For instance, my `Ball` class's constructor is:

```
Ball (std::string imageName, float screenWidth, float screenHeight)

```

The constructor then automatically centers the ball in the middle of the screen, since it knows the ball's width and height the dimensions the image it loads, and the screen width and height by the arguments it is passed.

I would rather be able to place the ball manually, and just take the exact `x` and `y` locations in the constructor:

```
Ball (std::string imageName, float x, float y)

```

But that would require the calling function to already know the ball's `width` and `height` in order to center the ball and when it creates a ball it'd have to write something like:

```
Ball ball("ball.png", ((SCREEN_WIDTH / 2) - (BALL_WIDTH / 2)),
((SCREEN_HEIGHT / 2) - (BALL_HEIGHT / 2)))

```

I know this may be personal preference, but I'm trying to figure out which way is generally accepted.

A similar issue occurs with my `Paddle` class. Its constructor argument list looks like this:

```
Paddle (std::string imageName, float screenWidth, float screenHeight, int player)

```

Since I set the location inside of the constructor, it's forced me to have a `player` flag so I know if the paddle is supposed to line up with the left or right hand side of the screen. If I took the exact `x` and `y` location in the constructor's argument list, I could figure out which player is which internally using math.

I'm thinking that if the calling function kept consts of all of their objects' widths and heights they could use those in all of their objects' constructors in order to manually set their starting position... but is this the best way to do this?

*EDIT:*

Now I'm thinking that it would be realistic to expect the calling function to know the center x and center y that it wants the object at, and the object itself can use those x and y coordinates to center itself using its own width and height.

I'm starting to think this may have been a silly question since it really depends on the type of game you're making and how you're using the specific classes. I appreciate any input!

# Answer
> 1 votes
I would assert that your first ball constructor, which takes the width and height of the *screen*, is not a good idea. The ball should not need to know about the boundaries of the screen; that encroaches upon a violation of the single responsibility principle for the ball object. A ball should be a ball, and store only information directly pertinent to it:

* its position in the world
* its size
* its sprite (I actually think this should go elsewhere as well, but that is a different topic)

A ball should have methods to query the size and bounds and a *higher level interface* (for example, a `Playfield` class) should be the one that determines if the ball is in within the boundaries of the playing field.

This allows you to, with no loss of generality:

* move the ball outside the play field if you need to (for some kind of special "exit the screen" transition effect, perhaps).
* move the ball between two different playing fields of different sizes (perhaps you have a split-screen two-player mode where you can "teleport" a ball into your opponent's field, for example).

If you define the ball's position as it's center, and the ball exposes its position and size information, you can easily compute the appropriate place to draw the ball's sprite from the code that does the rendering (which is partly why I feel like the sprite itself need not be part of the ball object).

(In other words, use your second constructor, the one that takes the position of the ball and not the screen size.)

---

Similarly with your `Paddle` class, I'd do the same. Just pass the position; the `Paddle` itself need not know which player it belongs to, that can also be handled by an external, higher level interface.

The basic idea I am advocating here is to keep individual interfaces as simple as possible, and compose the intended gameplay functionality by building up layers of increasingly higher-level interfaces that make use of lower-level ones. Like an onion, sort of.

You may also find the SOLID principles of object oriented design an interesting collection of reading.

# Answer
> 0 votes
This may add a little complication to your scenario but typically in games we use positions in 3D space even when working in 2D by using a transform.

Every object should have a local transform and is a child of the world transform, these transforms represent "model space" and "world space".

When determining an objects position the hardware needs to determine its location in world space by performing the translations in the "transform tree".

With 2D positioning typically we use a ray to determine a location of something by firing a ray from our camera we can determine a relationship between a pixel and an object in 3D space.

If you think about how your game will be rendered, you are sending information about a camera, its location, rotation, and the point it is looking at, you then define the object you want to place in your scene position it anywhere you want, it might be in front of the camera it might not, the hardware is really only concerned about what colour each pixel should be, how it determines that is based on a lot of information.

However ... All that said and done i am making a lot of assumptions here that basically depend on you taking a typical game engine and trying to implement something rather than say trying to place something on a windows form which is in fact based on a 2D coordinate system.

---
Tags: c++, sfml
---


# Question
Title: How do I create a horizontally centered "gravity line"?
Here's my ideal scenario: A game object (in blue) can change its horizontal velocity, but it will be pulled back by gravity (dotted gray arrows) toward a central vertical line (in red).

How can I do this?

# Answer
> 1 votes
You have variable centerlineX. If the sprite is to the left of it, accelerate with a 'gravity' vector, e.g. 9.81. And vice versa for the other side.

Presumably this should result in the sprite oscillating back and forth for ever, so you will need to add something to the mix to slow it down at a pleasing rate.

# Answer
> 0 votes
As karmington suggested, halve the screen width. Be sure to use a getter / setter to do this accordingl to the device's screen specs.

As for gravity, you would want to have a method within your update loop that checks the `x` position of your game object so when `gameObject.x` is less than `centerLine.x`, your gravity is multiplied by `-1`, flipping its direction and making the the `gameObject` move appropriately.

---
Tags: java, android, libgdx, box2d
---


# Question
Title: What are the possible techniques to optimize the lighting pass in a deferred shading renderer?
I am toying around with "modern" OpenGL (this is my first attempt, I am new to this) and I have been developping my own deferred shading renderer as an exercise.

I am using an FBO with the following attachments:

* DS : Depth/Stencil (GL\_DEPTH32F\_STENCIL8)
* RT0: Position (GL\_RGB16F)
* RT1: Normal (GL\_RGB16F)
* RT2: Albedo (GL\_RGB16F)
* RT3: Postprocessing buffer 0
* RT4: Postprocessing buffer 1

Depth + RT0, 1, 2 are filled first in one single geometry pass.

Then for each light source (point lights only for now, spheres are used as light volumes):

* Stencil pass to limit light calculation to where it actually has an effect
* Light pass: light contribution is accumulated in RT3

From this point on, I am only rendering a quad the size of the screen and fragment shaders are used to compute the next image.

Albedo (RT2) and Light (RT3) are blended into RT4: I now have my lit image.

I can enable more postprocessng shaders (FXAA, Depth of field, ...), in which case RT3 and RT4 are used for ping-ponging.

The thing is, even with no postprocessing, not that many lights (around 10) and a very simple scene (roughly 5k vertices), my frame rate drops like significantly as soon as I increase resolution or add more lights.

It looks like my light pass is responsible for most of this but how can I track down what exactly is slowing everything down? Are there any tricks to optimize it? Is there anything I am missing?

Thanks!

Light Fragment Shader for reference:

```
uniform sampler2D position;
uniform sampler2D normal;
uniform float screenw;
uniform float screenh;

uniform vec3 light_pos;
uniform vec3 camera_pos;
uniform vec4 diffuse;
uniform vec4 ambient;
uniform vec4 specular;
uniform float outer_radius;
uniform float inner_radius;

float specular_hardness = 100.0;

vec4 calc_point_light(vec3 p, vec3 n)
{
    vec3 light_dir = light_pos - p;
    float d_to_light = length(light_dir);

    light_dir = normalize(light_dir);

    vec3 eye_dir = normalize(camera_pos - p);
    vec3 half_vec = normalize(light_dir + eye_dir);

    float attenuation = (outer_radius - d_to_light) / (outer_radius - inner_radius);
    attenuation = max(min(attenuation, 1.0), 0.0);

    vec3 c = ambient.rgb * ambient.a;
    c += diffuse.rgb * max(dot(n, light_dir), 0.0) * diffuse.a;
    c += specular.rgb * pow(max(dot(n, half_vec), 0), specular_hardness) *
        specular.a;

    return vec4(clamp(c, 0.0, 1.0) * attenuation, 1.0);
}

void main(void)
{
    vec2 texcoord = gl_FragCoord.xy / vec2(screenw, screenh);
    vec3 p = texture2D(position, texcoord).xyz;
    vec3 n = texture2D(normal, texcoord).xyz;

    gl_FragColor = calc_point_light(p, n);
}

```

# Answer
> 2 votes
Some things you can try:

1. Don't use a separate position buffer. Instead reconstruct position from the depth buffer (bound as a texture).
2. Use `GL_RGB10_A2` for your normal buffer. This is two-third the size of `GL_RGB16F` and should provide enough accuracy.
3. `GL_RGBA8` should provide enough accuracy for your albedo buffer.
4. It should be fairly quick to try different depth buffer formats (`GL_DEPTH24_STENCIL8` or `GL_DEPTH_COMPONENT24`) to see if it makes any difference.

Following these recommendations should significantly reduce the texture traffic during your light pass, which might improve performance as bandwidth is often the limiting factor here.

---
Tags: opengl, optimization, deferred-rendering
---


# Question
Title: How can I project a vector on another vector?
I have a generic not normalized `Vector3 v1` and I want to calculate its component along another `Vector3 v2`. I used to normalize the vector I want to be the direction and then multiplying the other vector's magnitude for it. I can't really understand if it would also work to multiply the other vector (not just its magnitude), but I want to know if there is a lighter way to do it, since compute the magnitude of a vector implies evaluating a square root.

In code I would say

```
Vector3 v1;
Vector3 v2; v2.Normalize();
Vector3 resulting_v = v1.Length() * v2;

```

the other case (I am not sure if can work) would be

```
Vector3 v1;
Vector3 v2; v2.Normalize();
Vector3 resulting_v = v1 * v2;

```

or, if there is a better solution, I'm listening

# Answer
> 4 votes
In order to project a vector **v** on **u** you can start by this equation,

> len(v) * len(**u**) * cos(theta) = **v** . **u**

In order to the get the v component in the u direction. You can simply rearrange the equation by dividing on len(u), you get:

> len(**v**) * cos(theta) = (**v** . **u**)/len(**u**)

Since `len(**v**) * cos(theta)` is the **v** component in the **u** direction and is a scalar. we can simply make it a vector by multiplying we simply multiply by a normalized **u** direction.

> len(**v**) * cos(theta) = (**v** . **u**)/ len(**u**) * (**u** / len(**u**) )

And finally

> ProjVonU = ((**v** . **u**)/ len(**u**)) * ((**u** / len(**u**) ))

# Answer
> 0 votes
There is something wrong here.

Computing the component of V1 along V2 means that you want to know what portion of the lenght of V1 is projected to V2 in terms of the V2 length.

Lets say that V2 is 1Km long vector pointing North, your V1 vector is a 200m vector pointing to North/West; a point moved by V1 travels 100m to North and 100m to West that are both 0.1km. In this scenario the component of V1 along V2 is 0.1 (adimensional scalar).

If you multiply 0.1 by V2 then you get a 100m vector pointing to North (because 100m is 0.1 * 1Km). You can normalize your V2 so it becomes a 1m long vector pointing North; in this case the inner product will give you 100 so if you multiply by V2 normalized, you get the same result.

What you do in snipped 1 is wrong because you will get a 200m vector long pointing North, in other words you do not take into account the direction of V1.

---
Tags: c#, xna-4.0, vector
---


title: What is framerate-independent motion?

text:
# Question
Title: What is framerate-independent motion?
What is the definition of framerate-independent motion and why is important to have it in games?

# Answer
Framerate independent motion is when objects in your game move based on some criteria *other than* which rendering frame you are on. Typically this alternate criteria is the delta time since the *last* update.

A game loop that is **framerate-dependant** might look like this:

```
while(!done) {
  // update all objects:
  foreach (object in objects) {
    object.position += object.velocity;
  }

  // ...rendering, et cetera...
}

```

In this loop, if your game runs at 60 frames per second, every object is also updated 60 times per second. However, if your framerate increases or decreases, the rate at which objects update increases or decreases as well. Typically this is undesirable because the wall-clock time (that is, real time) is still exactly the same, so the user perceives the game objects moving much slower or much faster.

Old games typically did this, which is why if you try to run some of those older games on modern CPUs (even under emulation), they run *way too fast* to be playable, because your modern CPU can execute many more instructions per second.

By contrast, a **framerate-independent** loop which relies on delta time might look like this:

```
previous_time = get_current_time();
while(!done) {
  current_time = get_current_time()
  delta_time = current_time - previous_time;
  // update all objects:
  foreach (object in objects) {
    object.position += object.velocity * delta_time;
  }

  previous_time = current_time;

  // ...rendering, et cetera...
}

```

In the above example, the actual real time between successive updates is computed and used to scale the updates, which results in more correct update rates even if your frame rate changes. *Generally* this is a more desirable way to write your update loop. Not only does correct for disparity in update rates, it also lets you do interesting tricks like scale the `delta_time` (or set it to 0) to implement time-slowing effects (or pause the game logic).

Note that in practice one may want to set up multiple such timers (especially if you are going to make use of time scaling and want some objects to be unaffected by scaling).

Finally, it's occasionally desirable (especially for physics) to fix your time step.
> 6 votes

# Answer
If you would have your update and draw calls in the same loop, the draw performance would influence the update performance. Therefore you would not have framerate independent motion.

Lets say you have a pc with a really great graphics card and would be able to render @60fps, while your opponent would only have 30fps. Your machine would update your position, shots fired etc @60 times per second, while you opponent only 30.

This would give you substantional benefits.
> 1 votes

---
Tags: frame-rate, motion
---


# Question
Title: How can i create sprite sheet from 3d model (3D studio max)
I built simple 3D model of a car, with simple animation in which it's wheels are turning.

Now i want to create a sprite sheet, the only way i know how to do it, is to render manually 20 frames from the from, then combine them to a strip manually, then rotate it by 10 degrees, render 20 frames of animation again and combine them to a strip...

Is there a way to do it automatically ? With out rotating the scene manually and render it and combining .. it's a lot of work, takes more time then the modelling itself...

Thanks

# Answer
> 5 votes
After spending a week searching the web and checking every related blog post, i found the solution. http://www.denysalmaral.com/2012/04/px-spritesrender-3ds-max-scripted.html

This script renders and names the images perfectly, after it i combine them using "GlueIT"

Works like a charm,

Hope it will help others.

# Answer
> 1 votes
*Note: Was very nice finding an StackEnxchange answer pointing to my own script! ;)*

I'll would like to extend the answer for the original question:

You can automate this task in 3ds Max with its built-in scripted language: Maxscript, using the bitmap `render()` function and node `rotate()`. This example code will render active frames range animation by each angle of 4 views :

```
for i=0 to 3 do
(
 MyBitmap = Render camera:$Camera01 framerange:#active OutPutfile:MyFileName
 Rotate MyModelRoot 90
)

```

`render()` function use the same settings from Render Setup dialog (F10), like file format, bitmap dimensions, etc.

Then, for combining the result images into one big spread sheet we have `PasteBitmap()` function.

My script impementation also supports Render Elements, so we can export more rendering buffers, like Shadow Maps, Diffuse Map, z-Buffer or Object ID. But it still don't have the ability to combine rendered images into a single one. (Will be implemented in next version)

You can try also similar tools from other authors: http://www.scriptspot.com/3ds-max/scripts/sprite-render-script

---
Tags: sprites, 3dsmax, spritesheet
---


title: LibGdx drawing weird behaviour

text:
# Question
Title: LibGdx drawing weird behaviour
I am finding strange behaviour while rendering TextureRegions in my game, only when pausing it. I am making a game for Android, in Java with LibGdx.

When I comment out the line "drawLevelPaused()" everything seems to work fine, both running and paused. When it's not commented, everything works fine until I pause the screen, then it draws those two rectangles, but maybe ships are not shown, and if I comment out drawShips() and drawTarget() (just trying) maybe one of the planets disappears, or if I change the order, other things disappear and those that disappeared before now are rendered again. I can't find the way to fix this behaviour

I beg your help, and I hope it's my mistake and not a LibGdx issue. I use OpenGL ES 2.0, stated in AndroidManifest.xml, if it is of any help. Thank you in advance.

My Screen render method(game loop) is as follows:

```
@Override
public void render(float delta)
{
    Gdx.gl.glClearColor(0.1f, 0.1f, 0.1f, 1);
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

    controller.update(delta);
    renderer.render();
}

```

When world state is PAUSED controller.update does nothing at all, there is a switch in it. And renderer.render() is as follows:

```
public void render()
{
    int worldState=this.world.getWorldState();

    updateCamera();
    spriteBatch.begin();
    drawPlanets();
    drawTarget();
    drawShips();

    if(worldState==World.PAUSED)
    {
        drawLevelPaused();
    }
    else if(worldState==World.LEVEL_WON)
    {
        drawLevelWin();
    }
    spriteBatch.end();
}

```

And those methods are:

```
private void updateCamera()
{
    this.offset=world.getCameraOffset();
}

private void drawPlanets()
{
    for(Planet planet : this.world.getPlanets())
    {
        this.spriteBatch.draw(this.textures.getTexture(planet.getTexture()), (planet.getPosition().x - this.offset[0]) * ppuX, (planet.getPosition().y - this.offset[1]) * ppuY);
    }
}

private void drawTarget()
{
    Target target=this.world.getTarget();
    this.spriteBatch.draw(this.textures.getTexture(target.getTexture()), (target.getPosition().x - this.offset[0]) * ppuX, (target.getPosition().y - this.offset[1]) * ppuY);
}

private void drawShips()
{
    for(Ship ship : this.world.getShips())
    {
        this.spriteBatch.draw(this.textures.getTexture(ship.getTexture()), (ship.getPosition().x - this.offset[0]) * ppuX, (ship.getPosition().y - this.offset[1]) * ppuY, ship.getBounds().width*ppuX/2, ship.getBounds().height*ppuY/2, ship.getBounds().width*ppuX, ship.getBounds().height*ppuY, 1.0f, 1.0f, ship.getAngle()-90.0f);
    }

    if(this.world.getStillShipVisibility())
    {
        Ship ship=this.world.getStillShip();
        Arrow arrow=this.world.getArrow();
        this.spriteBatch.draw(this.textures.getTexture(ship.getTexture()), (ship.getPosition().x - this.offset[0]) * ppuX, (ship.getPosition().y - this.offset[1]) * ppuY, ship.getBounds().width*ppuX/2, ship.getBounds().height*ppuY/2, ship.getBounds().width*ppuX, ship.getBounds().height*ppuY, 1f, 1f, ship.getAngle() - 90f);
        this.spriteBatch.draw(this.textures.getTexture(arrow.getTexture()), (ship.getCenter().x - this.offset[0] - arrow.getBounds().width/2) * ppuX, (ship.getCenter().y - this.offset[1]) * ppuY, arrow.getBounds().width*ppuX/2, 0, arrow.getBounds().width*ppuX, arrow.getBounds().height*ppuY, 1f, arrow.getRate(), ship.getAngle() - 90f);

    }
}

private void drawLevelPaused()
{
    this.shapeRenderer.begin(ShapeType.FilledRectangle);
    this.shapeRenderer.setColor(0f, 0f, 0f, 0.8f);

    this.shapeRenderer.filledRect(0, 0, this.width/this.ppuX, PAUSE_MARGIN_HEIGHT/this.ppuY);
    this.shapeRenderer.filledRect(0, (this.height-PAUSE_MARGIN_HEIGHT)/this.ppuY, this.width/this.ppuX, PAUSE_MARGIN_HEIGHT/this.ppuY);

    this.shapeRenderer.end();

    for(Button button : this.world.getPauseButtons())
    {
        this.spriteBatch.draw(this.textures.getTexture(button.getTexture()), (button.getPosition().x - this.offset[0]) * this.ppuX, (button.getPosition().y - this.offset[1]) * this.ppuY);
    }

}

```

# Answer
> 3 votes
Although that's a little bit late, I'll still try to answer.

From the ShapeRenderer javadoc

"The standard use-pattern looks as follows:"

```
camera.update();
shapeRenderer.setProjectionMatrix(camera.combined);

shapeRenderer.begin(ShapeType.Line);
shapeRenderer.color(1, 1, 0, 1);
shapeRenderer.line(x, y, x2, y2);
shapeRenderer.rect(x, y, width, height);
shapeRenderer.circle(x, y, radius);
shapeRenderer.end();

```

Don't forget to call `setProjectionMatrix` before drawing a `ShapeRenderer` instance, otherwise you will get unexpected results.

You can get a projection matrix from `SpriteBatch.getProjectionMatrix()`

# Answer
> 1 votes
I know it's an old post but I ran into this problem today and none of these answers solved it. The correct answer is that you can't use ShapeRenderer between SpriteBatch().begin() and end().

OP's problem would be solved by ending the batch before drawLevelPaused():

```
public void render()
{
    int worldState=this.world.getWorldState();

    updateCamera();
    spriteBatch.begin();
    drawPlanets();
    drawTarget();
    drawShips();
    spriteBatch.end();

    if(worldState==World.PAUSED)
    {
        drawLevelPaused();
    }
    else if(worldState==World.LEVEL_WON)
    {
        drawLevelWin();
    }
}

```

---
Tags: java, android, libgdx
---


title: Dealing with angles in 3D

text:
# Question
Title: Dealing with angles in 3D
In 2D everything is easier to understand. I'm not enought experienced to join people who say that 3d is the same: you JUST need to add a dimension - THAT adding a dimension is my problem, bacause I can't easily visualize (or draw on paper) the situation I'm dealing with. So please don't say it is the same.

First let's talk of a concrete situation.

**Use case: bounding sphere intersection**

I have two entities colliding with theirs bounding sphere intersecting at a certain point. Let's consider two vectors, the velocity of the first entity `v1` and distance between boundingsphere centers `d`. If I want to get `v1` component along `d` I may want to do

```
V1 * Math.Cos(alpha)

```

with `alpha = Math.Atan2(...)`

**a.** My questions come now. `Math.Atan2(...)` takes 2 arguments, the first is the difference between Xs and second is the difference between Ys of the two vectors involved. So, since I'm working in 3D and not in 2D, should I assume that common practice is to consider a pair of dimenstion at time when dealing with angles in 3D? Since I'm a bit confused here, can someone tell me what's the best practice to follow in this case? (details would be appreciated here).

**b.** Then I have some information I'd like someone to confirm. When my double angle value is returned from the `Math.Atan2(...)`, I have my angle in radians. I read somewhere that this float value varies between `+- Pi`, reasonable. And also that `Math.Atan2(...)` always consider the lesser between the 2 angles, which is not important if you need to calculate `Cos(angle)` but you must keep it in mind if you wants to get the `Sin(angle)`. Is this how things work?

# Answer
Instead of an approach that relies heavily on trig (ie. your Atan2) as a means to solve the problem, 3d lends itself to a more linear algebra approach.

```
float v1ComponentAlongD = Vector3.Dot(v1, d); // look ma, no angles

```

Check out the last two paragraphs in Shawns blog here: http://blogs.msdn.com/b/shawnhar/archive/2010/02/12/doing-math-in-2d-vs-3d.aspx

So really I would recommend not wanting an answer to your a & b. Instead, get comfortable migrating away from trying to relate every problem to angles and instead relate it all to vector math (mainly the dot product and the cross product).

Generally in 3d, you won't get completely away from angles, but it sure is easier to do 3d when you can lean heavily on linear algebra and less on trig.
> 2 votes

---
Tags: c#, xna-4.0, angles
---


# Question
Title: Can someone explain Flappy Bird's physics to me?
I am having a difficult time trying to understand the Flappy Bird physics. I know it seems simple but I kind of suck at math. I am trying to see if I can make a simple game like this but it is just the dang physics that are throwing me off. I have something like gravity effecting the bird but when you click the screen and I add some amount to the y position but it doesn't look good. You guys have any ideas?

Stuff like:

```
velocity += -9.8 * Gdx.graphics.getDeltaTime();
position.y += 0.5 * velocity;

```

That is falling but when I tap the device I would like to know how to add upward force but when it loses it continue falling.

# Answer
> 10 votes
The bird falls continuously, and when the user taps the screen, it 'jumps' a bit. That's all there is to Flappy Bird's physics.

We use a variable called `vertSpeed` to keep track of the bird's vertical speed (positive if it goes up, negative if it falls down). `jumpSpeed` is a positive constant, to which the speed gets reset whenever the user taps the screen. This will immediately make the bird start its ascension. `fallingConstant` is again a positive constant, which accelerates the bird's decrease in vertical speed on each update. This makes the bird increase in speed when falling.

```
vertSpeed = 0;

method Update()
{
     if (PlayerTappedScreen)
     {
            vertSpeed = jumpSpeed;
     }
     Position.Y += vertSpeed * deltaTime;
     vertSpeed -= fallingConstant * deltaTime;
}

```

From here on, all you have to do is experiment with the values, to find a set that works best for you.

---
Tags: physics
---