# Question
Title: Grid based Collision Detection between circles
I am working on a 2d arcade game where I have 5 types of circles with different sizes: The ship, the missiles, and 3 types of monsters.

This is what it looks like:

Currently I'm using brute force collision detection where I check every missile vs. every monster without taking probability of collision into account. Sadly, this makes the process REALLY slow.

This here is my Grid class, but it's incomplete. I'd greatly appreciate your help.

```
    public class Grid {

    int rows;
    int cols;
    double squareSize;
    private ArrayList<Circle>[][] grid;

    public Grid(int sceneWidth, int sceneHeight, int squareSize) {
        this.squareSize = squareSize;
// Calculate how many rows and cols for the grid.
        rows = (sceneHeight + squareSize) / squareSize;
        cols = (sceneWidth + squareSize) / squareSize;
// Create grid
        this.grid = (ArrayList[][]) new ArrayList[cols][rows]; //Generic array creation error workaround
    }

The addObject method inside the Grid class.
    public void addObject(Circle entity) {
// Adds entity to every cell that it's overlapping with.
        double topLeftX = Math.max(0, entity.getLayoutX() / squareSize);
        double topLeftY = Math.max(0, entity.getLayoutY() / squareSize);
        double bottomRightX = Math.min(cols - 1, entity.getLayoutX() + entity.getRadius() - 1) / squareSize;
        double bottomRightY = Math.min(rows - 1, entity.getLayoutY() + entity.getRadius() - 1) / squareSize;

        for (double x = topLeftX; x < bottomRightX; x++) {
            for (double y = topLeftY; y < bottomRightY; y++) {
                grid[(int) x][(int) y].add(entity); //Cast types to int to prevent loosy conversion type error.
            }
        }
    }

```

But that's where I am at a complete loss. I'm not even sure the source code I provided is correct. Please let me know how to make the grid based collision work. I've read basically every tutorial I could get my hands on but without much effect. Thanks.

# Answer
> 0 votes
Given the image depicting a very manageable number of spheres you shouldn't have any problem checking every missile against every enemy.

You haven't shown us the relevant code, but my best guess it that you are not using basic sphere-to-sphere collision detection like you should.

Basically every sphere has a centre position and a radius. For every pair of spheres, if the distance between the centres is less than the sum of their radii the spheres intersect, otherwise they don't. If you implement this method right there should be no need to worry about performance unless you need to do a million or more checks per frame.

---
Tags: java, 2d, collision-detection, collision-resolution, grid
---


# Question
Title: How to make bullets follow a rotating sinewave pattern
I am trying to replicate the wave gun from Super Metroid where the bullets fly along a sine wave path. The cool part is that you can shoot in 8 directions and the bullet still follows the sine as if the whole sine function is rotated. I've tried using a 2d transformation to allow shooting in every angle but I cant get it to work. Here my code so far (JSFiddle.net). If you uncomment the line "Axis.dir += .02;" in the fiddle to start the rotation you'll notice that the black box doesn't follow it's axis at all.

```
var canvas = document.getElementById("can"),
  ctx = canvas.getContext("2d"),
  width = canvas.width, height = canvas.height,
  Axis = { x: width / 2, y: height / 3, dir: 0, vx: 0, vy: 0, speed: 4 },
  Sine = { x: Axis.x, y: Axis.y, angle: 0 },
  loop = function() {
      var rotatedX, rotatedY;
      // Draw
      ctx.clearRect(0, 0, width, height);
      ctx.fillStyle = "#F00";
      ctx.fillRect(Axis.x, Axis.y, 5, 5);
      ctx.fillStyle = "#000";
      ctx.fillRect(Sine.x, Sine.y, 10, 10);
      // Apply speed
      Axis.vx = Math.cos(Axis.dir) * Axis.speed;
      Axis.vy = Math.sin(Axis.dir) * Axis.speed;
      Axis.x += Axis.vx;
      Axis.y += Axis.vy;
      Sine.x = Axis.x;
      Sine.y = Axis.y + (Math.sin(Sine.angle) * 30);
      // Apply rotation
      rotatedX = Sine.x * Math.cos(Axis.dir) - Sine.y * Math.sin(Axis.dir);
      rotatedY = Sine.x * Math.sin(Axis.dir) + Sine.y * Math.cos(Axis.dir);
      Sine.x = rotatedX;
      Sine.y = rotatedY;
      Sine.angle += .03;
      Axis.dir += .02;
      // Keep drawn stuff on the screen
      if (Axis.x > width && Axis.vx > 0) Axis.x = 0;
      if (Axis.x < 0 && Axis.vx < 0) Axis.x = width;
      if (Axis.y > height && Axis.vy > 0) Axis.y = 0;
      if (Axis.y < 0 && Axis.vy < 0) Axis.y = height;
      window.requestAnimationFrame(loop);
  }
loop();

```

# Answer
It is actually supposed to be simple. There is an invisible anchor bullet moving like a normal game bullet would in a straight line (implementation not included).

You have the angle `alpha` in which the anchor bullet is moving and its position `px` & `py`. You also have the `amplitude` (how far does the sine wave expands) and it's `frequency` (how fast does it go up and down).

You also need the `time` to determine where the actual bullet is now.

To compute the position of the sine wave bullet, use this:

```
beta = alpha + PI / 2.0.; // offset angle by 90 degrees, only run once : doesn't change
// Loop
current_distance = amplitude * sin(time * frequency); // Inside loop
bullet.x = px + cos(beta) * current_distance;
bullet.y = py + sin(beta) * current_distance;
// Done

```
> 2 votes

---
Tags: 2d, javascript, rotation
---


# Question
Title: Drawing Colored Geometry in OpenGL using SDL
First off, I will confess I have asked the same question on stackoverflow, but I think this forum might be a better fit.

I am trying to combine 2 things using SDL:

1. Draw a **webcam** feed via an SDL\_Surface (from OpenCV).
2. Draw some plain **colored geometry** on top, using OpenGL.

The problem I have is that—I think—the geometry is textured by the screen texture that I draw the webcam feed in, even if I call `glDisable(GL_TEXTURE_2D)` right before drawing the quad. See the screenshot below, the square in the top-left is supposed to be *white*, but it seems to have the color of the **bottom-right** texel.

The code in my `Display` function is as follows:

```
// screen_surface_ contains a frame from the camera
SDL_UpdateTexture(screen_texture_, NULL, screen_surface_->pixels, screen_surface_->pitch);
SDL_RenderClear(renderer_);
SDL_RenderCopy(renderer_, screen_texture_, NULL, NULL);

glLoadIdentity();
glDisable(GL_TEXTURE_2D);
glColor3f(1.0, 1.0, 1.0);
glBegin( GL_QUADS );
  glVertex3f( 10.0f, 50.0f, 0.0f ); /* Top Left */
  glVertex3f( 50.0f, 50.0f, 0.0f ); /* Top Right */
  glVertex3f( 50.0f, 10.0f, 0.0f ); /* Bottom Right */
  glVertex3f( 10.0f, 10.0f, 0.0f ); /* Bottom Left */
glEnd( );

glColor3f(1.0, 1.0, 1.0);
SDL_RenderPresent(renderer_);

```

You can view all the code of relevant functions here.

I got a blanket answer saying "Don't mix SDL and OpenGL draw code"; as addressed in this bug report. But that would mean I'm simply stuck waiting for that bug to be fixed, so I'm still looking for a way to disable texturing after `SDL_RenderCopy` has been called.

**Edit:** I've confirmed that it's indeed still using the `screen_texture_`. Setting the `texCoord` to values between 0-100 shows a part of the webcam feed. (I tried 0-1 first but then I read that texCoords are different for rectangular images).

# Answer
> 0 votes
(Crosspost from stackoverflow)

I have fixed the problem by simply adding

```
glcontext_ = SDL_GL_CreateContext(window_);

```

to the `SDL_Init` code. I think all my calls to openGL functions (like `glDisable(GL_TEXTURE_2D)` were applied to the wrong context. Explicitly creating a context from SDL sets the right context to be active, I'm guessing.

**Something else to look out for**: when using *textured* geometry after using `SDL_RenderCopy`; I had to make sure to reset

```
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);

```

before calling `glTexImage2d`, because it uses

> GL\_UNPACK\_ROW\_LENGTH if it is greater than 0, the width argument to the pixel routine otherwise

(from the OpenGL docs)

---
Tags: opengl, sdl
---


title: java tile based game :tile lag fix

text:
# Question
Title: java tile based game :tile lag fix
hi I have a game where it reads a txt file and loads a map 0 represents air and 2 represents dirt I have a class for each tile as well as a tilemap I will show u my code. the problem is it lags like all hell. is there something I am doing wrong or is there something I need to add like rendering a certain amount of tiles at a time.(I don't know how to do that).it lags really bad. here is my code:

public class tilemap {

```
private int x;
private int y;

private int tilesize;
private static int[][] map;
private int mapwidth;
private int mapheight;
public static Image img;
public static int camx,camy;
public static BufferedImage stone;

public ArrayList<air> air = new ArrayList<air>();
public ArrayList<dirt> dirt = new ArrayList<dirt>();

public String sl;

public tilemap(String s,int tilesize){
    this.tilesize = tilesize;

    try{

        BufferedReader br = new BufferedReader(new FileReader(s));

        mapwidth = Integer.parseInt(br.readLine());
        mapheight = Integer.parseInt(br.readLine());

        map = new int[mapheight][mapwidth];

        String del = " ";
        for(int row = 0; row < mapheight; row++){
            String line = br.readLine();
            String[] tokens = line.split(del);
            for(int col = 0; col < mapwidth; col++){
                map[row][col] = Integer.parseInt(tokens[col]);
            }
        }

    }catch(Exception e){}

    try{
    }catch(Exception e){

    }
}

public void update(){
    //checkcollision();
      for (int i = 0; i < air.toArray().length; i++) {
            air.get(i).tick();

        }
      for (int i = 0; i < dirt.toArray().length; i++) {
            dirt.get(i).tick();

        }

}

public void draw(Graphics g){
    for(int row = 0; row < mapheight; row++){
        for(int col = 0; col < mapwidth; col++){

             int rc = map[row][col];

             int mr = tilesize*row;
             int mc = tilesize*col;

              if(rc == 0){
                  air.add(new air(mc,mr));
              }
              if(rc == 2){
                  dirt.add(new dirt(mc,mr));
              }

              for (int i = 0; i < air.toArray().length; i++) {
                air.get(i).render(g);

              }

              for (int i = 0; i < dirt.toArray().length; i++) {
                dirt.get(i).render(g);

              }

        }
    }

}

```

}

public class air {

```
public int y;
public int x;
public Image img;

public Rectangle r = new Rectangle(x,y,40,40);

public air(int x,int y){
    this.x = x;
    this.y = y;
}
public void tick(){

}

public void render(Graphics g){
     ImageIcon i2 = new ImageIcon("res/water.png");
        img = i2.getImage();
        g.drawImage(img,x - tilemap.camx,y-tilemap.camy,null);

}

```

}

public class dirt {

```
public int y;
public int x;
public Image img;

public Rectangle r = new Rectangle(x,y,40,40);

public dirt(int x,int y){
    this.x = x;
    this.y = y;
}
public void tick(){

}

public void render(Graphics g){
     ImageIcon i2 = new ImageIcon("res/dirt.png");
        img = i2.getImage();
        g.drawImage(img,x - tilemap.camx,y-tilemap.camy,null);

}

```

}

# Answer
You are loading a graphic *for every tile in every frame*. Load it once at application startup that sould improve the speed dramatically.
> 2 votes

---
Tags: java, tiles, tilemap, lag
---


title: why is my OpenGL texture transparent?

text:
# Question
Title: why is my OpenGL texture transparent?
I have a terrain in OpenGL, and two textures which I am combining using GLSL mix() function. Here are the textures I am using.

Now I am able to combine and mix these two textures, but for some reason, when I render the textures on the terrain, the terrain becomes transparent. I render the LHS texture first, and then I render the RHS texture with alpha channel, I don't understand why it is transparent.

Here is an interesting fact, in the screenshot, you can see the result of the terrain when rendered on Nvidia GPU, when I render the same thing on interl HD 3k, I get different result. This result is how it is supposed to be, nothing is transparent in this following screenshot.

Here is my fragment shader code..

```
void main()
{
vec4 dryTex   = texture( u_dryTex, vs_texCoord *1 );
vec4 grassTex = texture( u_grassTex, vs_texCoord *1 );
vec4 texColor1= mix(dryTex, grassTex , grassTex.a);
out_fragColor = texColor1;
}

```

# Answer
> 3 votes
There might be multiple problems with your code.

In your fragment shader you mix in a color which is transparent, this causes the end result to be partially transparent too. For this you could do the following:

```
out_fragColor = vec4( texColor1.rgb, 1.0 );

```

This forces fully opaque alpha, and keeps the color the same. This might not be enough, based on the setting of `glBlendFunc`, as it might blend based on the background alpha or something else. See the reference for details.

Another problem is that you are rendering your terrain using blending. Generally it is better to turn blending off when it is not needed, this might improve performance as well.

You can do this by `glDisable(GL_BLEND);` , and when you need it again turn it on by `glEnable(GL_BLEND);`

The resulting image vary on different graphics cards because of the different driver implementations. The default value of `glBlendFunc` might be different, hence the difference in the pictures.

---
Tags: opengl, c++, textures, glsl
---


# Question
Title: Does the protagonist's age matter in a 3rd person shooter?
There have been very young characters in modern games that wield weapons including firearms before. Two good examples include Ellie from The Last of Us, and Clementine from The Walking Dead. Whilst I don't support the idea of having gun wielding children as characters, I do understand the context of use in the above two examples and the points being made.

I am designing the concepts of a 3rd person action game. The protagonist is a modern male adolescent (about 13 years old) and their age is important because the game's design is centred around the idea of growth and having the protagonist learn and achieve milestones through the game's progression. Being an action game there is combat and weapons including firearms. What I would like to know is, is there particular considerations I need to take with the issue of having firearms and a very young protagonist? At the moment the gameplay progression has the protagonist starting of as completely unarmed, having to initially rely solely on hand to hand combat and other stealth and platformer based skills to progress and learn new abilities. I would like to make more weapons and eventually firearms available to the protagonist, but have their use be completely up to the player and not a necessity for game progression. Most importantly I would like to make sure that the finished game does not come across as promoting the underage use of guns.

So is the protagonist age an important consideration in this type of game genre, or not? For example would I need to make sure I include a tutorial scene where the protagonist is taught how to fire a gun by an adult?

# Answer
To get serious legal advice contact a lawyer. Games exist where under-aged characters perform violent acts: Bully

I can't say if it's ethical (your game idea). I think it isn't because it gives the impression that kids are allowed to use firearms against other kids. We all know that only adults are allowed to play dress-up, wear uniform and commit mass murder of complete strangers and only if it's sanctioned by their government.

So I think your game idea is possibly not legal for both good reasons and hypocritical reasons.

On second thought, Kickass is all about kids killing others and Battle Royal is kids killing kids so maybe.. You could pull it off in game land somehow but I doubt any publisher will agree to help with it.
> 1 votes

---
Tags: game-design, character
---


# Question
Title: Simple collision detection implementation
I'm making a game with C++ where the program extracts the lines out of an image (via openCV), stores them in an std::vector\< std::vector\< int \> \> and the builds a tile map out of it which is used for a simple jump'n'run game (with SFML).
Having everything else implemented, I still struggle when it comes to implementing the collision detection. I have tried several approaches (i. e. the second approach on this site) but always failed. This means that the player is able to move over obstacles as there was no collision detection.
So I need a simple, fail-safe way of implementing a collision detection (or maybe just the algorithm) when using a tile map.
I don't want my code or my former approach corrected, but I'm asking for a simple way to implement a collision detection in a 2d tile-based game.

# Answer
> 1 votes
Heere are the generic steps, where are you stuck?

Alright.

1. Create a bounding box for the character. It needs to have a center `(x, y)`, `width` and `height` measured in the smallest game units used.
2. Write code that checks if a bounding box intersects with a tile.
3. When you want to move the character (lets say) to the left, check if by moving it one unit to the left, it will cause the bounding box to intersect with a solid tile. If it does, don't move it left (The same with all other directions).

How to check for intersection between rectangles?

Assuming these are the corners on the left side of your bounding box `(x, y0)`, `(x, y1)` (x is the same on both).

1. Check where they are positioned (in the tile-map 2d array) after moving one step right: ie `(x+1,y0)` `(x+1,y1)`.
2. Check in which tile they are positioned in. ie `(x+1) / TILE_SIZE`, `y0 / TILE_SIZE` same with `y1` for the other corner.
3. Iterate from the tile the upper corner is to the one the bottom corner is in. ie :

```
for(i = tile_y0; i <= tile_y1; i++){
  // False means the character cannot move in that direction.
  if tile_map(tile_x, i).is_solid() return false;
  else return true; // It can keep moving

```

The same works for every direction of movement.

---
Tags: c++, collision-detection, physics, tilemap, sfml
---


# Question
Title: Pathfinding in non tile-based 2d map (maybe potential field)
I am developing a top-down 2d zombie shooter in AS3. I have implemented collisions against segments (line from point a to point b), polygons (array of points, convex) and round obstacles (center and radius) Player and enemies are basically moving round obstacles, with different radii.

Now, I'm having trouble with zombie AI's pathfinding. I have read about potential fields, and I found it fascinating, but I can't figure out how to adapt it to a non tile-based map. I can calculate the distance from a point to the closest obstacle, and get the obstacle repulsive potential in that point. I don't know how to get the player's attracting potential in that point though. In tile-based maps you use the A\* algorithm, considering every walkable tile as a node. This is my first problem.

Once I have calculated the player's attracting potential in a point, what I get is a Number. In tile-based maps, I would test this number against the potential of the 8 adjacent tiles, and move the enemy to the tile with the lowest potential. In my non-tile based map instead I do not have a fixed set of tiles to test, so I can't understand how to get the moviment vector to apply to the enemy. This is my second problem.

If I, say, set a waypoint every x\*y pixels, I could use it as the centre of a tile, but that sounds very unelegant, mainly because enemies would be forced to move along the 8 directions of adjacent nodes.

Should I forget PFs and try a different approach?

# Answer
> 2 votes
Use finite differences. The potential field method relies on computing a function which is at a minimum around your target, and increases going away from that point. This acts as an "attraction" for the zombies, in your case. Then, obstacles are given a repulsive force, by adding in a term for

```
P(x) = p_target(x) + sum(p_o(x) for o in obstacles)

```

Here p\_target should be small around the target, and grow larger the further you are. Typically:

```
p_target(x) = |x - target|

```

i.e. the potential is just the distance to the target location (|\*| is length). Similarly, a common :

```
p_obstacle(x) = 1 - sqrt(min(|x - closest(x,obstacle)| / delta, 1))

```

where closest(x,obstacle) is the closest point on the given obstacle to the point x, and delta is the distance at which the obstacle is ignored by the zombies. This defines our potential function.

Now we want the gradient of this function, which we can use finite differences to obtain. We evaluate the vector `<P(x + <0.1,0>)-P(x), P(x + <0,0.1>)-P(x)>`, and normalize it. This gives us a direction to go in. Note that the discrete version of this is exactly the "evaluate at all tiles and pick the lowest one" that you describe - this is the continuous version.

Potential fields do not require any sort of tiles or subdivision of space, such as quadtrees, etc., as they are defined continuously through space. However, in our formulation of the obstacle function, the influence falls to zero when you are further than `delta` from an obstacle: so such spatial division would be helpful in only considering the obstacles that actually have an effect. Otherwise the sum above is over *all* obstacles, which isn't very efficient. Also, by calculating this function on a grid first, each zombie does not need to re-evaluate the sum, which could get expensive if you aren't being clever about which obstacles you are summing over. The absence of grids is one of the benefits of this method.

On of the drawbacks is that zombies will not route around obstacles, the can get "stuck" inside of rooms if the door is on the other side from where the player is. Perhaps this is desirable for zombies, creatures of lower intelligence? If you want your enemies to intelligently route, then you could try a hybrid approach.

# Answer
> 0 votes
I did some research and checked and benchmarked some methods. I found this library which could be easily used with a navigation mesh to create a fluid motion.

http://gamma.cs.unc.edu/RVO2/downloads/

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


# Question
Title: RK4, Derivatives, Understanding Game Physics
Gafferon Games has a great article on RK4 Integration for building physics simulations which can be found here: Integration Basics

Personally my mathematics and physics knowledge could use improvement. I feel comfortable within the realm of vector mathematics, trig, some stats (I've had to use linear line regression formulas for software, etc. ), and basically most things high school level to first year college.

Now to the question, I've read this article, downloaded the associated source and debugged line by line to try and get an understanding of what is happening and still feel like I'm clearly not getting what I'm looking at. I've searched the internet trying to find the "For Dummies" versions, frankly I learn a little differently and staring at formulas all day with the emphasis on memorization isn't going to cut it as I need to understand what is happening so I can be flexible applying it.

So here's what I think I understand so far, but I am hoping someone else can clarify or completely correct me. The RK4 uses a Euler step, then bases that to move forward in time to calculate several more essentially Euler steps(?) and determines using a weighted sum what the best position and velocity is for the next frame?

Furthermore that acceleration method (converted into AS3):

```
private function acceleration(state:State, time:Number):Number
{
    const k:int = 10;
    const b:int = 1;
    return - k*state.x - b*state.v;
}

```

takes a constant mass(10) and force(1)? and returns some weird calculation I have no idea why...-mass * position - force * velocity? what?

Then for my last bit of confusion, in the evaluate methods which look like (AS3):

```
private function evaluateD(initial:State, time:Number, dtime:Number, d:Derivative):Derivative
{
    var state:State = new State();
    state.x = initial.x + d.dx*dtime;
    state.v = initial.v + d.dv*dtime;
    var output:Derivative = new Derivative();
    output.dx = state.v;
    output.dv = acceleration(state, time+dtime);
    return output;
}

```

We store a new state with the time step, then set a derivative to return...I sort of understand this as it's used in the approximation process, but what is this!:

```
output.dx = state.v;
output.dv = acceleration(state, time+dtime);

// ok I get we are getting the new velocity since v = a * t, obviously I
// don't what acceleration() is returning though.

```

We set the derivative output change in position to the states new velocity? Huh?

Lastly this test simulation runs doing this:

```
var state:State = new State();
state.x = 100;
state.v = 0;

t = 0;
dt = 0.1;

while (Math.abs(state.x)>0.001 || Math.abs(state.v)>0.001)
{
    trace(state.x, state.v);
    integrate(state, t, dt);
    t += dt;
}

```

So we are setting a new state with a positional value of 100, and a velocity of 0? What is the point of this simulation if we have no velocity...

Anyway, needless to say I'm pretty confused and have drifted off planet Earth. Hoping someone out there can clarify this for me.

# Answer
RK4 is an example of a *numerical integrator*. Euler integration is a similar concept, but it is much less precise. Numerical integration is not exact, but much better for a computer to handle in a real-time situation such as a game. The reason that you use RK4 instead of Euler is that RK4 takes into account the integration of the second and third derivatives (acceleration and jerk), and thus fits the analytical solution much better.

RK4 is essentially a Taylor series expansion of the differential equation that defines acceleration with respect to displacement and velocity. This allows you to integrate forces that depend on these quantities, such as in constraints and even universal gravitation. Taylor series expansions are useful in programming as computers can evaluate them very efficiently.

The `acceleration` function used is an example is a simple damped spring system, **not** gravitational. `k` is Hooke's spring constant, and `b` is used to damp the system (remove energy). For pretty much all spring-related constraints in your engine, you will want to damp them as numerical errors can cause a huge accumulation of energy, causing the simulation to explode. If you were using Euler integration, this would be much worse.

With regards to `acceleration()`, a more complete physics engine will calculate both linear and angular accelerations based on forces (torques). The forces to sum could include gravity (constant or based on Universal Gravitation), buoyancy, and springs (most constraints can be modeled using stiff springs).

Your third question is easy to answer. In kinematics, there are three basic quantities: displacement (position), velocity, and acceleration. Acceleration is the derivative of velocity, which is the derivative of displacement (both with respect to time). A derivative is just the rate at which something changes. `Derivative.dx` means "the derivative of `State.x`".

Because the simulation assumes that the spring is anchored at the origin and has a rest length of zero, a displacement of 100 means that the particle will start to oscillate. The test simulation ends when the particle is not moving and is close to the origin.
> 7 votes

---
Tags: physics, mathematics, rk4
---


title: Manage shader parameters

text:
# Question
Title: Manage shader parameters
I'm making some test with OpenGL and I've got a problem with my application design. Currently, I've got something like that in pseudo code:

```
// Ask to draw a given scene.
renderer->drawScene( myScene, myCamera );

// Here is what I do in the renderer
for( auto& mesh : scene->getElements() )
{
    this->draw(mesh);
}

// And here is what my draw method do.
// First geometry stuff.
context->setVertexFormat( mesh->geometry->vertexFormat );
context->setVertexBuffer( mesh->geometry->vertexBuffer ); // Use VAO is available.
context->setIndexBuffer( mesh->geometry->indexBuffer );

// Second, material stuff.
context->setProgram( mesh->material->program );
mesh->material->program->setParameter( "model", mesh->transform->position );
mesh->material->program->setParameter( "uCamera", camera.matrix );
context->setBlendMode(mesh->material->blendMode);

// Finally draw.
context->draw( mesh->material->drawingMode, mesh->geometry->indiceCount );

```

The problem is present with shader attributs, by exemple from main loop:

```
int main()
{
    while()
    {
        // I want change texture offset for the mesh N°7, that will change it for every mesh.
        myMesh7->material->program->setParameter("offset", 15.f);

        renderer->DrawScene(myScene, myCamera);
    }
}

```

How can I have a flexible design? A Shader/Program is shared with others meshes, so in the case where I would change "color" or "offset" attribute in my shader for only one mesh it's not possible. How can I handle that?

(I don't think it will be good to copy somewhere shader attributs per mesh)

Thanks for your help

# Answer
> 1 votes
The thing to realize when trying to design a rendering architecture is that OpenGL (and GPU programming in general) is all about registers and state. You have to bind buffers and textures and then issue draw calls, not issue draw calls that come with data.

Although this seems limiting, it's very efficient. Because GPUs often offload operations like texture filtering to dedicated silicon (like texture units), these operations are very fast. The downside is that there are a limited number of specialized units, and they are unable to access just anything in memory. Similar to CPUs, GPUs work best when their memory is in a quick register or cache, and binding operations allow the programmer to guarantee that a variable, buffer, or texture is loaded into a register or assigned to a piece of dedicated silicon.

Many operations that deal with binding are very expensive. They may need to flush the pipeline and DMA data from system memory to video memory. In particular, texture and shader binding are very expensive operations. To make sure that you aren't wasting too much time, you want to ensure that you are binding resources as little as possible.

The best way to do this is to define a high-level rendering system that transforms a list of renderables into a sequence of commands (that are implemented as OpenGL function calls). A renderable associates various pieces of rendering data to represent elements such as objects and lights, while a command maps to one or more related OpenGL function calls.

Internally, this system is essentially just a big sorting algorithm. Renderables are sorted according to their most "expensive" pieces of rendering data. Primarily, renderables would be sorted by texture first and shader next, while uniform changing is not a big priority for sorting. You can think of it as organizing the renderables into a tree, where the leaves are draw calls and the nodes are bindings. You can then walk the "tree" and produce the commands.

As an example, here's an unsorted list of renderables:

* Small rock (rock texture, static shader)
* Player (skin texture, animated shader)
* Door (wood texture, static shader)
* Big rock (rock texture, static shader)
* Cart (wood texture, animated shader)

And here would be an optimized command sequence to draw them (assuming one texture unit):

1. Bind static shader
2. Bind rock texture
3. Draw small rock
4. Draw big rock
5. Bind wood texture
6. Draw door
7. Bind animated shader
8. Draw cart
9. Bind skin texture
10. Draw player

# Answer
> 0 votes
I assume you know in loop when it is time to draw mesh in a different way. What you can do is this

While drawing every object

```
if it is time for your special mesh
set uniform variable x = 1 (you should use the corresponding gluniform1i(...)
else
set uniform variable x = 0

```

and in your shader program, you will have a uniform integer x in the code

```
if ( x == 0 )
do it usual way
else if ( x == 1)
do it the specific way

```

This way, when it is time for your specific mesh, your C++ code will set x to 1 using gluniform1i and your shader code will behave differently for that code. You can add as many parameters as you like to control your shader code using uniforms.

Alternatively, you can create a different program with separate shader code that includes only the part that should be executed when it is time for the specific mesh, and you can enable it when the right time comes (but this is a very bad idea for a minor change)

---
Tags: architecture, shaders, opengl-es2
---


# Question
Title: Enemy Spawning method in a Top-Down Shooter
I'm working on a top-down shooter akin to *DoDonPachi*, *Ikaruga*, etc. The camera movement through the world is handled automatically with the player able to move inside of the camera's visible region.

Along the way, enemies are scripted to spawn at particular points along the path. While this sounds straightforward, I could see two ways to define these points:

1. Camera's position: 'trigger' spawning as the camera passes by the points
2. Time along path: "30 seconds in, spawn 2 enemies"

In both cases, the camera-relative positions would be defined as well as the behavior of the enemy.

The way I see it, the way you define these points will directly affect how the 'level editor', or what have you, will work.

Would there be any benefits of one approach over the other?

# Answer
> 7 votes
I would suggest placing the spawn positions actually ON the background map as nodes that are visible from some sort of map editor. You can represent a shmup spawn with two variables:

1. Position they are first visible from, which is best visualized as a point
2. Distance from bottom screen when you should spawn them.

Then you can visualize the distance from bottom of screen as a vertical line pointing downward from the spawn node (which could be visualied as a greyed out version of the enemy or some such). When the bottom of the screen touches that line it will spawn. This allows you to do all of enemy editing completely in some sort of visual editor, and give you an overview of the entire flow of the game.

# Answer
> 7 votes
Just a though, the camera's position to spawn would probably be more flexible since you could modify the path without having to worry about a large domino effect.

If you go with time spawns then it will be a huge pain to add or remove path because you will have to modify a lot of enemy spawns.

Another issue I see is tweaking the camera speed. Do you really want to go and have to tweak enemy spawns just because you've made the camera move a little faster or slower? Plus you would need to play through the level a horrible amount of times just to find spawn times or tweaks for them.

# Answer
> 2 votes
I'd strongly recommend not moving "the camera" at all; consider the player and enemies in the same fixed coordinate space at all times. Enemies and background scrolling should both be matched to an independent timeline. It makes all the math easier.

# Answer
> 1 votes
I'd go for camera position. Using time will make it rather hard if you want to have an enemy path match up with some graphics in your map file (like enemies following a curved path). Also it allows you to speed up the scroll without changing spawnpoints.
The flipside is that speeding up the scroll will make enemies come faster. Which could be considered a plus (speedup would be difficulty up) or a negative (scroll speed influences pacing).

# Answer
> 1 votes
I am also working on a space shooter game. What i did is I used an empty gameobject called GameController. added a script component called GameController.cs which is controlling the spawning part like,

* Store a list of spawning points \[array\]
* Give each enemy a specific weight and points. weight controlling enemy spawning rate if an enemy has high weight got good possibility to pick in each level.
* Then each time check Current level and Choice a random number, if number is less then weight, spawn that associate enemy. I hope it helped.

http://www.youtube.com/watch?v=VqFJsU63GRo

# Answer
> 0 votes
I would place them on the large map background and include their initial movement path on that map. That way I could change the camera path later in a meaningful way instead of needing to change both path and the timing separately.

---
Tags: game-design, level-design, shoot-em-up
---


# Question
Title: updating 2d array to contain chunk of larger 2d array - for 2d tile map
What i need help with is how can i get a chunk of a large 2d char array and update it so i am only drawing enough tiles to cover the screen?

Currently, i load all the chars from a text file and store them in an array. I then create a smaller array:`char[][] toDraw = new char[height][width]` which gets the first height\*width area of chars from the larger array like this:

```
  public void filterMap() {
    for(int i = 0; i < height; i++) {
        for(int j = 0; j < width; j++) {
            toDraw[i][j] = MapLoader.mapData[i][j];
        }
    }
}

```

I then draw the map using this drawMap method:

```
public void drawMap(Canvas canvas) {
    for(int i = 0; i < height; i++) {
        for(int j = 0; j < width; j++) {
            if(getBitmap(toDraw[i][j]) != null) {
            canvas.drawBitmap(getBitmap(toDraw[i][j]), x + (j*tileSize), y + (i*tileSize), null);
            }
        }
    }
}

```

note the int x and y are what i increment to move the map, getBitmap(char c) returns a Bitmap from a char, MapLoader.mapData is the 2d array that the text file loads into.

I have tried a few ways of using an offset in the toDraw arrays index to scroll the data relevant to the x,y location but they have been buggy/failed.

So, does anybody have a link to how things like this can be done (I have tried but have found none that help) or could someone with experience in 2d games please tell/show me how this should be done.

Currently my code will get a area from the larger array and draw it to the screen, the only problem is updating the data in the toDraw array. thanks.

The game is made for android but is not included in tags because i dont feel it is relevant to the problem

# Answer
If you only want to work with a small chunk, then only iterate through that chunk.

```
for(int i = BOTTOM_BOUND; i < TOP_BOUND; i++) {
    for(int j = LEFT_BOUND; j < RIGHT_BOUND; j++) {
        // Do something with the chunk
        toDraw[i][j] = MapLoader.mapData[i][j];
    }
}

```

That loop will only update a small rectangle formed by the constants, anytime you want to update just the chunk just iterate using the same four points.
> 1 votes

---
Tags: 2d, tilemap, graphics-programming
---


# Question
Title: How can I properly rotate a 2D vector in the "flipped" XNA client space?
In my 2d XNA game, because `SpriteBatch` treats world space as client space and has positive Y axis down and negative up, I've built my game's world space with that coordinate system too. However, I've hit a snag when I try to rotate a position around the origin using a matrix.

```
var p1 = new Vector2(95f, 40f);

var m = Matrix.CreateRotationZ(MathHelper.ToRadians(90));

var p2 = Vector2.TransformNormal(p1, m);

```

This results in p2.X == -40 and p2.Y == 95. If there's an object that is positioned relative to another object and that other object rotates, the child object gets swung around the parent object in the opposite direction because the matrix works in the positive Y axis up and negative down coordinate system.

What's the best way to account for this? Negate the Y value before and after transforming?

**EDIT**: To get more detailed I am trying to do a transformation like this, where child rotates with parent:

I though I would be able to multiply the matrices from the child object up through each of its parents' transform matrices in order to get its final world position, scale, and rotation that can be passed to `SpriteBatch.Draw`. Unfortunately the combined translations and rotations don't work out properly with the inverted Y axis.

# Answer
What ended up being the solution was to transform the individual position, rotation, and scale of each object with the combined matrices of each parent going up when rendering in world space. Previously I was multiplying the matrix representing the position, rotation, and scale of the object with the parent matrices and then decomposing the final matrix. Now everything works as expected even with the positive Y axis going down and rotation is always clockwise.
> 0 votes

# Answer
Because the y-axis is flipped, you need to negate the angle.

The x-axis is in the same place, so angles of 0 and pi are the same (the x-axis and the negative x-axis). Negating the angle has the effect of negating the y-axis, because y=sin(a), and sin(-a)=-sin(a). Thus just negating the angle (right before making the Z matrix) has the effect you desire. Be very careful with multiple coordinate systems: I would advise sticking to one for as much as possible, even if that means adding a bunch of negations to get the angles to do what you expect.
> 1 votes

# Answer
It can be also done with pure math, take a look:

```
b.rotation = a.rotation;
b.Position.X = a.Position.X+(Math.Cos((b.rotation+offset)/180*Math.PI)*distanceOffset);
b.Position.Y = a.Position.Y+(Math.Sin((b.rotation+offset)/180*Math.PI)*distanceOffset);

```

Where:

* "**b**" is the small cirlce around the big one
* "**a**" is the big circle
* "**offset**" is the offset around the circle in degrees
* "**distanceOffset**" is the small circle's distance from the big circle (big circle radius+small circle radius)

Code in work. (link works, but the host is slow)
> 0 votes

---
Tags: xna, mathematics, matrix, monogame, transformation
---


# Question
Title: How do I change the size and specific height values of Unity generated terrain?
I'm having problems with terrain scripting while trying to do a infinite-world with Unity's terrain generation.

How do I change the terrain height at specific points? And how do I set the amount of terrain generated?

Edit: What I'm having problem with is doing that **from a script**, from the editor is plain easy.

# Answer
Nevermind. After an hour of trying I have found the method.

Well, it's actually a variable, and it's a Vector3 called "size", who could have guessed it?

I still can't believe I've missed it for that long.

For heights, still as obvious, "SetHeights method";
> -1 votes

---
Tags: unity, terrain, procedural
---


# Question
Title: Opengl Obj with multiple textures. Jpg texture don't display
Hi i have problem with jpg textures. DDS is working good but jpg is not. This is my function to load JPG texture. In debuger i see that this works but i dont see anything.

```
char * a =(char *) path.c_str();
text = ilutGLLoadImage(a);

return text;

```

My function to bind texture. It works for dds but not for jpg. My second question is that if i have n-textures for object should can i use only one uniform?

```
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, Textures[0]);
glUniform1i(TextureID, 0);

```

EDIT Ok my problem is with vertex, fragment shadder

# Answer
> 0 votes
I think you are loading the image twice, `ilutGLLoadImage` actually loads the image to the GPU memory (it's a wrapper above OpenGL functions), you are also calling `glBindTexture(GL_TEXTURE_2D, text);` and `glTexImage2D` after that, that should trigger an error because `text` is already used, you only need to use one of them; if you use the .

When binding your Texture you need to make sure that you are actually binding the correct texture and texture unit. Which is actually hard to tell from your code.

To explain the issue I just notice that you always bind `0` in the `glUniform` function. Each texture unit have an id strating from \[0, n\]. So in order to correctly bind your textures, first bind the texture object to the correct texture unit. Then pass the texture unit to the shader using `glUniform`, this unit will have the texture that was bind.

```
//Step 1 This essentially binds  Textures[0] to TextureUnit0
glActiveTexture(GL_TEXTURE0); // This is texture unit 0
glBindTexture(GL_TEXTURE_2D, Textures[0]); // This binds the texture object to the texture unit.

// This passes the texture unit (not the object) to the shader.
glUniform1i(TextureID, 0);

 // This will pass texture unit 1 (you should bind a texture object
glUniform1i(TextureID, 1);like you did for the first unit.

```

Make sure to understand the difference between texture units and texture objects.

The reason this is a confusing terminology, is that because of legacy that openGL carries. The designers wanted to support old code. So they couldn't add another param to the texture functions (couldn't change the OpenGL Interface).

---
Tags: opengl, c++, assimp
---


title: Libgdx - Collision position - Box2D

text:
# Question
Title: Libgdx - Collision position - Box2D
I'm currently developing my own game but I'm facing a little problem. I am trying to figure out how to get the position of a fixture (collision) between two entities.

For example this:

(the grey rectangle is the player and the greens is an entity (not moving)).

With this code :

```
        Array<Contact> contacts = levelDatas.world.getContactList();
        try {
            for(Contact contact : contacts) {
                if(contact.getFixtureA().equals(playerBody.getFixtureList().get(0))) {
                    levelDatas.bodyIsWall(contact.getFixtureB().getBody());
                }
                if(contact.getFixtureB().equals(playerBody.getFixtureList().get(0))) {
                    levelDatas.bodyIsWall(contact.getFixtureA().getBody());
                }
            }
        } catch(GdxRuntimeException exp) {
        }

```

I get all the collision between a player and something else. But my problem is that I want to know where the collision is happening (on the left? on the right? bottom? top?). We can see that if there is a collision between 2 entities, a little point is draw. Anyone have a tip to give me the position of the collision?

Thanks

# Answer
When two fixtures collide, there are most of times multiples collisions between them, you can see those collisions with :

```
for (int i = 0; i < contact.getWorldManifold().getNumberOfContactPoints(); i++) {
   contact.getWorldManifold().getPoints()[i].x;
   contact.getWorldManifold().getPoints()[i].y;
}

```

1st you check all collsion number, then you will get the X and Y position of the given 'i' index.
> 3 votes

---
Tags: java, collision-detection, libgdx
---


# Question
Title: How to best utilize depth buffer precision
Are there strategies to minimize depth buffer precision problems with hyperbolic depth buffers, such as the ones resulting from perspective projection matrices, or depth buffers in general?

For example, graphics APIs usually give an option to change the depth range, which might influence precision. It's possible to linearize non-linear depth buffers, for whatever reason. There's the option of floating point depth buffers, and non-floating point depth buffers. It's possible that changing the information in projection matrices has a result on the resulting range & precision of the depth buffer.

How do all of these things interact with the resulting range & precision, or with each other, and how do I get the maximum out of my depth buffer? Are there general good practices one should adopt, regardless of project specifics?

# Answer
> 4 votes
Floating-point depth buffers would enhance range if they actually stored non-normalized depth values. You have a choice between 32-bit fixed-point or 32-bit floating-point depth, for all other bit-depths the depth buffer is always fixed-point. So compared to a 24-bit or 16-bit depth buffer, a floating-point depth buffer always has enhanced precision... but the reason has ***nothing*** to do with the fact that you switched to floating-point. Depth values are generally already in the range **0.0** \- **1.0** whether you use floating-point or not, so by themselves nothing is gained.

An interesting property of floating-point depth buffers, however, is that if you invert the depth range and use a floating-point depth buffer you can often improve the consistency in precision near and far. Typically because of the way perspective projection works precision is distributed with a bias toward points close to the near plane. Emil Persson has a great discussion of the situation here. He also has a few articles to his name on the subject while he worked at AMD, though they are less pertinent.

Also, you should never linearize the depth buffer. This requires writing a new value to the depth buffer ***after*** rasterization, and will prevent hardware optimizations such as Hierarchical Z-Buffering and Early Depth Tests from functioning as intended. Do everything you can to maximize the precision of the non-linear depth buffer, rather than fundamentally altering what is stored in the depth buffer.

As a capstone to this entire disucssion, you should consider the following article, because it discusses the ramifications of all of the representations I mentioned above in terms of re-constructing position from depth. The takeaway point is that inverse perspective depth (`1 – Z/W, 32-bit floating point`) is nearly as good as linear depth, and it still benefits from hardware Z-buffer optimizations.

---
Tags: rendering, depth-buffer
---


# Question
Title: Textures not displaying. Problem with fragment and vertex shaders
Hi i have newbe question. I am sending to gpu textures unit and they dont display. This is simple version of my fragment and vertexshader. (More complicated version also dont work with other textures than DDS but maybe simpler version will tell you what newbe mistake i made)

```
for (unsigned int i = 0; i < textures.size(); i++){
    glActiveTexture(GL_TEXTURE0+i);
    glBindTexture(GL_TEXTURE_2D, Textures[i]);
    // Set our "myTextureSampler" sampler to user Texture Unit 0
    glUniform1i(TextureID, i);
}

```

This is my simple fragmentshader

```
#version 330 core

// Interpolated values from the vertex shaders
in vec2 UV;

// Ouput data
out vec3 color;

// Values that stay constant for the whole mesh.
uniform sampler2D myTextureSampler;

void main(){

    // Output color = color of the texture at the specified UV
    color = texture2D( myTextureSampler, UV ).rgb;
}

```

This is my simple vertexshader

```
#version 330 core

// Input vertex data, different for all executions of this shader.
layout(location = 0) in vec3 vertexPosition_modelspace;
layout(location = 1) in vec2 vertexUV;

// Output data ; will be interpolated for each fragment.
out vec2 UV;

// Values that stay constant for the whole mesh.
uniform mat4 MVP;

void main(){

    // Output position of the vertex, in clip space : MVP * position
    gl_Position =  MVP * vec4(vertexPosition_modelspace,1);

    // UV of the vertex. No special space for this one.
    UV = vertexUV;
}

```

EDIT this corrected version but still something dont work. If i had DDS everything was working OK but jpg textures all time i have problems.

EDIT i have correct number of textures but they looks diffrent than original

# Answer
You are using sampler 0 for every single texture, you should fix this call `glActiveTexture(GL_TEXTURE0);` so that it looks more like:

```
for (unsigned int i = 0; i < textures.size(); i++){
    glActiveTexture(GL_TEXTURE0 + i);
    glBindTexture(GL_TEXTURE_2D, Textures[i]);
    // Set our "myTextureSampler" sampler to user Texture Unit 0
    glUniform1i(TextureID, i);
}

```
> 0 votes

---
Tags: opengl, c++, textures, shaders
---


# Question
Title: How can I teleport seamlessly, without using interpolation?
I've been implementing Bukkit plugin for creating toggleable in-game warping areas that will teleport any catched entity to other similar area.

I was going to implement concept of non-Euclidean maze using this plugin, but, unfortunately, I've discovered that doing `Entity.teleport()` causes client to *interpolate movement while teleporting*, so player slides towards target like Enderman and receives screen updates, so for a split second all underground stuff is visible.

While for "just teleport me where I want" usage this is just fine, it ruins whole idea of *seamless teleporting*, as player can clearly see when transfer happened even without need to look at debug screen.

Is there possibility to somehow disable interpolating while teleporting without modifying client, or maybe prevent client from updating screen while it's being teleported?

# Answer
> 2 votes
Vanilla Minecraft implemented seamless relative teleports recently (link), you might be able to get away with just having the server execute a command:

```
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "tp player 0 0 0");

```

---
Tags: minecraft-modding, bukkit, non-euclidean
---


# Question
Title: Using SpriteBatch with BasicEffects and layerDepth creates negative Z values?
Simply: Why don't all of these sprites draw? What do I need to do to make them draw?

I'm trying to use SpriteBatch.Draw with the layerDepth parameter to help reduce overdrawn. However I can't get it to work properly. It keeps outputting negative Z values when I try to use it with AlphaTestEffect! I've created a basic test case below to show the problem of.

The code for creating the effects and matrixes are based on this :"SpriteBatch and custom shaders in XNA Game Studio 4.0" from the XNA blog.

I think the projection matrix given should make sense, looking at the docs for CreateOrthographicOffCenter. But for some reason it doesn't! Can any one figure out why and tell me, please?

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

namespace SpriteBatchTest
{
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        BasicEffect basicEffect;
        AlphaTestEffect alphaTestEffect;
        Texture2D mysprite;

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

        protected override void Initialize()
        {
            base.Initialize();

            Viewport viewport = this.GraphicsDevice.Viewport;
            Matrix projection = Matrix.CreateOrthographicOffCenter(0, viewport.Width, viewport.Height, 0, 0, 1);
            Matrix halfPixelOffset = Matrix.CreateTranslation(-0.5f, -0.5f, 0);

            basicEffect = new BasicEffect(this.GraphicsDevice);
            basicEffect.World = Matrix.Identity;
            basicEffect.View = Matrix.Identity;
            basicEffect.Projection = halfPixelOffset * projection;

            basicEffect.TextureEnabled = true;
            basicEffect.VertexColorEnabled = true;

            alphaTestEffect = new AlphaTestEffect(GraphicsDevice);
            alphaTestEffect.VertexColorEnabled = false;
            alphaTestEffect.DiffuseColor = Color.White.ToVector3();
            alphaTestEffect.AlphaFunction = CompareFunction.Greater;
            alphaTestEffect.ReferenceAlpha = 0;
            alphaTestEffect.World = Matrix.Identity;
            alphaTestEffect.View = Matrix.Identity;
            alphaTestEffect.Projection = halfPixelOffset * projection;

        }

        protected override void LoadContent()
        {

            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            mysprite = Content.Load<Texture2D>("test");

            // TODO: use this.Content to load your game content here
        }

        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed ||
                Keyboard.GetState().IsKeyDown(Keys.Escape))
                this.Exit();

            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            this.GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.CornflowerBlue, 1.0f, 0);

            spriteBatch.Begin();
            //drawn
            spriteBatch.Draw(mysprite, new Vector2(100, 100), Color.White);
            //drawn
            spriteBatch.Draw(mysprite, new Vector2(500, 100), null, Color.White, 0.0f, Vector2.Zero,
                 Vector2.One, SpriteEffects.None, 0.50f);
            spriteBatch.End();

            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp,
                DepthStencilState.Default, RasterizerState.CullNone, basicEffect);
            //drawn
            spriteBatch.Draw(mysprite, new Vector2(150, 150), Color.White);
            //neg z, not drawn
            spriteBatch.Draw(mysprite, new Vector2(500, 150), null, Color.White, 0.0f, Vector2.Zero,
                 Vector2.One, SpriteEffects.None, 0.50f);
            spriteBatch.End();

            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp,
                DepthStencilState.Default, RasterizerState.CullNone,
                alphaTestEffect);
            //drawn
            spriteBatch.Draw(mysprite, new Vector2(200, 200), Color.White);
            //not draw - negative Z
            spriteBatch.Draw(mysprite, new Vector2(500, 200), null, Color.White, 0.0f, Vector2.Zero,
                Vector2.One, SpriteEffects.None, 0.50f);
            spriteBatch.End();

            //drawn
            spriteBatch.Begin();
            spriteBatch.Draw(mysprite, new Vector2(200, 100), null, Color.White, 0.0f, Vector2.Zero,
                            Vector2.One, SpriteEffects.None, 0.50f);
            spriteBatch.End();

            //not draw - negative Z
            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp,
                DepthStencilState.Default, RasterizerState.CullNone, basicEffect);
            spriteBatch.Draw(mysprite, new Vector2(250, 150), null, Color.White, 0.0f, Vector2.Zero,
                Vector2.One, SpriteEffects.None, 0.60f);
            spriteBatch.End();

            //not draw - negative Z
            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp,
                DepthStencilState.Default, RasterizerState.CullNone, alphaTestEffect);
            spriteBatch.Draw(mysprite, new Vector2(300, 200), null, Color.White, 0.0f, Vector2.Zero,
                            Vector2.One, SpriteEffects.None, 0.70f);
            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}

```

# Answer
The problem was that XNA sprite's use a Right Hand coordinate system and the DirectX API by default uses a Left Hand coordinate system by default. So my Z values would get flipped as XNA has positive Z going into the screen and DX has negative Z going into the screen.
> 1 votes

---
Tags: xna, spritebatch, depth-buffer
---


# Question
Title: How do I draw an animated object in OpenGL ES?
I have a VBO, which I initialise like this (just an example):

```
- (void)setupVBOs {

    GLuint vertexBuffer;
    glGenBuffers(1, &vertexBuffer);
    glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(Vertices), Vertices, GL_STATIC_DRAW);

    GLuint indexBuffer;
    glGenBuffers(1, &indexBuffer);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(Indices), Indices, GL_STATIC_DRAW);

}

```

As you can see, I'm using `GL_STATIC_DRAW`, which is good for visually unchanging objects (not including translations and such).

How do I draw animated objects though? I mean things that might be changed by user interaction. This video is a good example. It is obvious OpenGL is being used, as the vertices are manipulated by gestures.

How is it done? by changing the `x` `y` `z` coordinates on every touch? Are they using `GL_DYNAMIC_DRAW`? Is this hard?

# Answer
Create a VBO with a `GL_DYNAMIC_DRAW` or `GL_STREAM_DRAW` flag. This is used to give the OpenGL implemetation a hint of where to allocate the memory and enable certain optimizations, for example the data could be cached or not, stored in system memory or graphics memory.

**Dynamic** means the data will be changed frequently (specified and used repeatedly)

**Stream** means the data will be changed every frame (specified once and used once).

Regarding the video, since you are going to update the buffer frequently, once you create your buffer, you can use glMapBuffer which will give you the ability to map the buffer in the GPU to the client address and directly read and/or write on it relative to the returned pointer, depending on the specified access policy. This way you can update the vertices frequently without copying the entire buffer every time.
> 3 votes

---
Tags: opengl, opengl-es, opengl-es2, control
---


title: Game Loop: Best way to limit the fps?

text:
# Question
Title: Game Loop: Best way to limit the fps?
My game-loop looks like this:

```
        public void run() {
            init();

            final double amountOfTicks = 60.0;
            double ns = 1000000000.0 / amountOfTicks;
            long time = System.currentTimeMillis();
            long lastTime = System.nanoTime();
            long now = 0;
            double delta = 0;
            int tickCount = 0;
            int renderCount = 0;

            while(running) {

                now = System.nanoTime();
                delta += (now - lastTime) / ns;
                lastTime = now;

                if(delta >= 1) {
                    tick();
                    tickCount++;
                    delta--;
                    render();
                    renderCount++;
                }

                if(System.currentTimeMillis() - time >= 1000) {
                    time += 1000;
                    System.out.println(tickCount + " Ticks, " + renderCount + " FPS");
                    tickCount = 0;
                    renderCount = 0;
                }

            }
            stop();

        }

```

In the variable "amountOfTicks" i can set how many ticks i want per second. The amountOfTicks are here the same as the fps which i have. With this solution my console prints "60Ticks, 60 FPS", but the problem is, that the CPU-performance with this method is too low. I have only 60 Ticks and only 60 FPS, but the whole while-loop is still running through as fast as my pc can.

The only thing how i can improve the cpu-performance is, if i let the thread for 1ms or so sleeping. But is this solution not dirty? This solution will maybe work on my (relative good pc), but on a other with with less CPU-performance the 1ms sleep maybe are waste, because of this the game maybe can not reach the 60FPS of this?

# Answer
> 3 votes
There are two ways of achieving this, one would be a *variable timestep*, with that the game would seem consistent, regardless how fast the computer of the player is.

The other way would be a *fixed timestep*, there you will know how long each single timestep would be, also regardless how fast the computer is.

For more information on Game loops you can look at this site.

Here are some examples:

**Variable timestep**

```
public void gameLoop()
{
   long lastLoopTime = System.nanoTime();
   final int TARGET_FPS = 60;
   final long OPTIMAL_TIME = 1000000000 / TARGET_FPS;

   // keep looping round til the game ends
   while (gameRunning)
   {
      // work out how long its been since the last update, this
      // will be used to calculate how far the entities should
      // move this loop
      long now = System.nanoTime();
      long updateLength = now - lastLoopTime;
      lastLoopTime = now;
      double delta = updateLength / ((double)OPTIMAL_TIME);

      // update the frame counter
      lastFpsTime += updateLength;
      fps++;

      // update our FPS counter if a second has passed since
      // we last recorded
      if (lastFpsTime >= 1000000000)
      {
         System.out.println("(FPS: "+fps+")");
         lastFpsTime = 0;
         fps = 0;
      }

      // update the game logic
      doGameUpdates(delta);

      // draw everyting
      render();

      // we want each frame to take 10 milliseconds, to do this
      // we've recorded when we started the frame. We add 10 milliseconds
      // to this and then factor in the current time to give
      // us our final value to wait for
      // remember this is in ms, whereas our lastLoopTime etc. vars are in ns.
      try{Thread.sleep( (lastLoopTime-System.nanoTime() + OPTIMAL_TIME)/1000000 )};
   }
}

```

**Fixed timestep**

```
private void gameLoop()
{
   //This value would probably be stored elsewhere.
   final double GAME_HERTZ = 30.0;
   //Calculate how many ns each frame should take for our target game hertz.
   final double TIME_BETWEEN_UPDATES = 1000000000 / GAME_HERTZ;
   //At the very most we will update the game this many times before a new render.
   //If you're worried about visual hitches more than perfect timing, set this to 1.
   final int MAX_UPDATES_BEFORE_RENDER = 5;
   //We will need the last update time.
   double lastUpdateTime = System.nanoTime();
   //Store the last time we rendered.
   double lastRenderTime = System.nanoTime();

   //If we are able to get as high as this FPS, don't render again.
   final double TARGET_FPS = 60;
   final double TARGET_TIME_BETWEEN_RENDERS = 1000000000 / TARGET_FPS;

   //Simple way of finding FPS.
   int lastSecondTime = (int) (lastUpdateTime / 1000000000);

   while (running)
   {
      double now = System.nanoTime();
      int updateCount = 0;

      if (!paused)
      {
         //Do as many game updates as we need to, potentially playing catchup.
         while( now - lastUpdateTime > TIME_BETWEEN_UPDATES && updateCount < MAX_UPDATES_BEFORE_RENDER )
         {
            updateGame();
            lastUpdateTime += TIME_BETWEEN_UPDATES;
            updateCount++;
         }

         //If for some reason an update takes forever, we don't want to do an insane number of catchups.
         //If you were doing some sort of game that needed to keep EXACT time, you would get rid of this.
         if ( now - lastUpdateTime > TIME_BETWEEN_UPDATES)
         {
            lastUpdateTime = now - TIME_BETWEEN_UPDATES;
         }

         //Render. To do so, we need to calculate interpolation for a smooth render.
         float interpolation = Math.min(1.0f, (float) ((now - lastUpdateTime) / TIME_BETWEEN_UPDATES) );
         drawGame(interpolation);
         lastRenderTime = now;

         //Update the frames we got.
         int thisSecond = (int) (lastUpdateTime / 1000000000);
         if (thisSecond > lastSecondTime)
         {
            System.out.println("NEW SECOND " + thisSecond + " " + frameCount);
            fps = frameCount;
            frameCount = 0;
            lastSecondTime = thisSecond;
         }

         //Yield until it has been at least the target time between renders. This saves the CPU from hogging.
         while ( now - lastRenderTime < TARGET_TIME_BETWEEN_RENDERS && now - lastUpdateTime < TIME_BETWEEN_UPDATES)
         {
            Thread.yield();

            //This stops the app from consuming all your CPU. It makes this slightly less accurate, but is worth it.
            //You can remove this line and it will still work (better), your CPU just climbs on certain OSes.
            //FYI on some OS's this can cause pretty bad stuttering.
            try {Thread.sleep(1);} catch(Exception e) {}

            now = System.nanoTime();
         }
      }
   }
}

```

---
Tags: game-loop, first-person-shooter
---


# Question
Title: Triangular grid and rendering to a texture (Direct3D 11)
Is it possible to render vertex data from a triangular grid into a texture with a same size (i.e. 3x3 vertices to 3x3 pixels - each pixel is representing one vertex)?

Consider following situation. I have a grid (3x3 to keep it simple) and in a vertex shader is a computation of Z coordinate (imagine it like some wave model of a water surface). So, each vertex has some Z value, and I need to store these values into a texture (for a comparison with a next frame). A texture is set as a render target and has a same size as the grid.

How to render a precise Z value (coordinate) of a vertex into appropriate pixel? I mean, my dilemma is a fact that rasterizer gets three vertices and interpolates their values by default, so values stored in pixels are not precise at all.

# Answer
If you are using DX11, you could use DirectCompute style and its buffers (`RWStructuredBuffer` and `StructuredBuffer`) instead of texture. They should be writable from shaders.
> 1 votes

---
Tags: textures, directx, rendering, grid, rasterization
---


title: How do I create indoor scene lighting?

text:
# Question
Title: How do I create indoor scene lighting?
I'm building the inside of a space ship in Unity as POC. I need info on scene lighting. Rooms, corridors or just in general how to make an enclosed scene look great with lights.

Keep in mind this is indoors and I can't really use the Directional Light and have to rely on realistic light sources.

Thanks!

# Answer
First off, most of the time indoor environments in games have lightmaps. The lighting of the scene is baked into textures applied to the scene, rather than expensive lighting calculations done on the fly: http://docs.unity3d.com/Documentation/Manual/LightmappingInDepth.html

However, while lightmaps give very good results on static geometry like level walls, they are useless on dynamic geometry because they are pre-calculated. For maximum realism in lighting of dynamic objects, modern games are increasingly turning to a technique called deferred lighting, in which lighting and shading is a separate render pass from colors. It's only available in Unity Pro: http://docs.unity3d.com/Documentation/Components/RenderTech-DeferredLighting.html
> 3 votes

---
Tags: unity, level-design
---


title: Combine textures with coordinates

text:
# Question
Title: Combine textures with coordinates
Is it possible to add one texture to another texture, at specific coordinates? Like if I want to add a small texture(16x16) to big texture (1368 x 768) with coordinates ( 100, 100) so the small texture goes to specific coordinates (100, 100 ).

# Answer
Yes, glTexSubImage may be what you are looking for.
> 0 votes

---
Tags: opengl, c++, 2d, textures
---


# Question
Title: problem with texcoord at post effect (quad rendering)
I have this shader:

```
float4x4 View;

struct VS_INPUT
{
    float2 Position : POSITION;
    float2 TexCoord : TEXCOORD;
};

struct PS_INPUT
{
    float4 Position : SV_Position;
    float2 TexCoord : TEXCOORD;
};

PS_INPUT VsMain(VS_INPUT _Input)
{
    PS_INPUT Output;

    Output.Position = mul(View, float4(_Input.Position, 0, 1));
    Output.TexCoord = _Input.TexCoord;

    return Output;
}

float4 PsMain(PS_INPUT _Input) : SV_Target
{
    float4 Color = float4(_Input.TexCoord, 0.0f, 1.0f);

    return Color;
}

technique11 Render
{
    pass P0
    {
        SetVertexShader(     CompileShader(vs_5_0, VsMain()));
        SetHullShader(       NULL);
        SetDomainShader(     NULL);
        SetGeometryShader(   NULL);
        SetPixelShader(      CompileShader(ps_5_0, PsMain()));
    }
}

```

and this vertices:

```
const float g_QuadVertices[] =
{
//   X     Y     U     V
    0.0f, 1.0f, 0.0f, 0.0f,
    1.0f, 1.0f, 1.0f, 0.0f,
    0.0f, 0.0f, 0.0f, 1.0f,
    1.0f, 0.0f, 1.0f, 1.0f
};

```

It is a full screen quad and everything is fine. Only my Texcoord is always the same on every vertice? I got a dark yellow picture on my screen! It seems that the pixel shader don't interpolate (u,v between pixels).

The TexCoord inside the pixel shader is always u = 0.5 and v = 0.5.

I tried to create my own sampler with:

```
D3D11_SAMPLER_DESC SamplerDescription;

SamplerDescription.Filter         = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
SamplerDescription.AddressU       = D3D11_TEXTURE_ADDRESS_CLAMP;
SamplerDescription.AddressV       = D3D11_TEXTURE_ADDRESS_CLAMP;
SamplerDescription.AddressW       = D3D11_TEXTURE_ADDRESS_CLAMP;
SamplerDescription.MipLODBias     = 0.0f;
SamplerDescription.MaxAnisotropy  = 0;
SamplerDescription.ComparisonFunc = D3D11_COMPARISON_NEVER;
SamplerDescription.BorderColor[0] = 0;
SamplerDescription.BorderColor[1] = 0;
SamplerDescription.BorderColor[2] = 0;
SamplerDescription.BorderColor[3] = 0;
SamplerDescription.MinLOD         = 0;
SamplerDescription.MaxLOD         = 0;

Res = m_pDevice->CreateSamplerState(&SamplerDescription, &m_pSamplerState);

```

but nothing has changed.

# Answer
Don't declare the sampler inside the shader, but create an ID3D11SamplerState\* outside and upload it while drawing by ID3D11DeviceContext::PSSetSampler(slot,count,sampler); I had the same problem with DX11.

You might create a sampler like this:

```
    D3D11_SAMPLER_DESC samplerDesc;
    samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
    samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
    samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
    samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
    samplerDesc.MipLODBias = 0.0f;
    samplerDesc.MaxAnisotropy = 16;
    samplerDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
    samplerDesc.BorderColor[0] = 0;
    samplerDesc.BorderColor[1] = 0;
    samplerDesc.BorderColor[2] = 0;
    samplerDesc.BorderColor[3] = 0;
    samplerDesc.MinLOD = 0;
    samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;
    g_pd3dDevice->CreateSamplerState(&samplerDesc, &mapSampler);

```
> 0 votes

---
Tags: textures, directx11, graphic-effects, post-processing
---


# Question
Title: When is a quadtree preferable over spatial hashing?
I'm making a 2d platformer with lots of objects at the same time. They're all AABB collision detected. I first tried a quadtree to decrease the number of of objects to check, tried a few different configurations, but it didn't prove as effective as I needed. I implemented a spatial hash and it's way more efficient, the number of objects to check for each collision went down drastically.

Is there a case when doing 2d collision detection using a quadtree is preferable over spatial hashing? According to my tests, it seems spatial hashing always ends up with less objects to be tested for collision?

I haven't done timing over the algorithms, but is hashing simply very expensive or difficult to implement when you're, for example, coding in C? Worth noting is that I'm writing the game in javascript, where you have hashing "for free".

Here's the comparison, did I overlook something?

# Answer
> 12 votes
The major advantage of a quad tree is that it allows you to discard whole groups of buckets from consideration very quickly.

For example, let's assume that I have a quad tree with six levels. At its lowest level, that's 32x32 boxes; 1024 boxes comprising that bottom, most-detailed level. For comparison, we'll also consider a "spatial hash" -- a flat grid which also contains 32x32 boxes, 1024 boxes in total. (the quad tree has more than 1024 boxes in total, since it also contains larger boxes at its higher levels)

Let's assume that there are no collidable objects in the system -- all the boxes of our quad tree and our flat grid are completely empty.

If you're testing the collisions of something which is large enough that its bounding box intersects all of those boxes, and you're using a flat grid, you have to check every single one of those 1024 boxes to see if there's even anything in them.

But if you're using a nested quad tree, the very topmost level can tell you that there are no other objects in the system, and so you only have to look at that single box to know that you're not going to find collisions deeper in the tree -- you can stop testing immediately.

Similarly, if the objects only exist in certain regions of the quad tree, the quad tree will naturally guide your search through only potentially relevant boxes, whereas the grid requires you to check every single intersected box, because you have no way to know in advance which grid squares will have objects in them. If much of your quad tree is empty and you're doing large, complicated queries (say, huge camera frustums instead of small, simple rectangles), then you may find that you're iterating over far fewer boxes in total if you do your tests against something using a tree structure, rather than a flat grid. And that can make a big difference.

All of which isn't to imply that a tree structure is always the right choice, of course. Flat grids are ideal for the situation you have in your example -- dense clouds of objects pretty much evenly spread everywhere in the world, and we're doing simple, inexpensive collision tests. Absolutely a grid is likely to be the optimal approach in that case!

---
Tags: collision-detection, quadtree, space-partitioning
---


# Question
Title: Update function in html5 canvas game isn't working properly
Jsfiddle : http://jsfiddle.net/seekpunk/6eeKH/15/

the code :

```
if (this.collection.length > 0) {
    if (((this.collection[0].blockX + this.collection[0].blockW) >= cw)
       || (this.collection[0].blockX <= 0)) {
        this.collection[0].blockSpeed *= -1;
    }
    this.collection[0].blockX += this.collection[0].blockSpeed;
}

```

the first block from top is drawn twin and i can't figure out why i guess the problem is in drawing the levels can someone please help me figure out what i did wrong in my code

# Answer
> 0 votes
You're adding blocks using `addBlocks` method every frame in function `Level1`, all your blocks are duplicated loads of times. In `Blocks.draw()`, print the size of the collection and you'll see what I mean.

Make sure you set up your level once, then change the state of it, do not add all the blocks on every frame.

---
Tags: html5, html-canvas
---


# Question
Title: Where should the collision response/resolution code go?
I've got a collision response/resolution function that does the same for any pair of two entities. It's is in the `World` class right now.

But right before that function is invoked, I have some entity-specific logic:

1. A specific pair of entities should never have their collisions resolved (this is literally to keep the player from hitting itself with a carried object)
2. When two specific entities collide, an event should be triggered

Because of this, I'm starting to wonder if I should move the collision resolution function as a method into `Entity`, that'd allow me to use polymorphism. However, this sound very messy to me: If both entities involved in a collision can resolve it, how can I figure out which one should do it?

Is there another way to move these special cases out of `World`?

# Answer
What you need is a separation of the collision resolution and specific logic steps, so the collision process is broken up into three separate steps, each of which is well-defined. Here's a simple diagram to show how it would work:

```
                    Contacts         Reduced Contacts
Collision Detection -------> [Logic] ---------------> Collision Resolution

```

So really, you now have a collision *pipeline*, with two fixed-function steps (detection and resolution) and a programmable step (logic). First, the collision detection step takes a set of entities and spits out a set of collision contacts. The entity-specific logic removes contacts that should not be applied, and reacts accordingly to contacts that should be. Finally, the collisions are resolved.

Instead of calling two virtual methods for each contact pair, I'd build a table mapping predicates and events to a pair of collision types (which are stored in the contact data). For example, if you wanted to have an item that disabled collisions between the player and certain walls, you could add a predicate to the table that always returned `False` (destroying the contact in the process) for contacts between `Player`s and `PassThroughWall`s. If you needed it, adding scripting support to this contact modification table would be quite easy.
> 3 votes

---
Tags: physics, architecture, software-engineering
---


# Question
Title: How do I draw tile in a side-on perspective?
All the tutorials I've found regarding using tiles in game engines refer to games with an isometric or top-down view, much like this:

I want to make a "beat em up"-game, where the view is tilted.

Examples include *Streets of Rage*, *Golden Axe*, *Knights of the Round* and *Castle Crashers*. They look much like this:

How do I draw a tile compatible with that view?

I'm using Photoshop and Inkscape.

# Answer
> 0 votes
The illusion of the camera being on the side comes from the background and characters being drawn from a side-on view. There are no special perspective tricks going on.

Let's have a closer look at that *Knights of the Round* screenshot.

First, I copied a region from the bottom left and moved it toward the right until I noticed that the grass at the bottom matched up:

Observe the grass at the bottom. It appears not to change, because it's the same grass tile repeated at that point.

Clearly, the ground doesn't tile here though... Let's move that cutout region a little further:

Sure enough, the ground is made of repeating rectangular sprites too.

# Answer
> 0 votes
It is not really that hard. It is mostly the same but you just apply some foreshortening on the ground layer (e.g. by transforming by 50% in height). For the background you just create your tiles with a side view instead using top view.

If you have problems understanding perspective you should maybe practice a bit doodling boxes from different angels/perspectives on paper first.

---
Tags: 2d, tiles, perspective
---


title: Get the 8 corners of camera frustrum?

text:
# Question
Title: Get the 8 corners of camera frustrum?
I'm doing shadow mapping for directional lights and I'm trying to get 8 corners of the camera frustrum as a bounding box for the geometry, but I have no idea how. The goal is like in the image below (from another source):

The purple lines represent the final bounding box I am trying to achieve.

From what I know, I am supposed to do use the inverse of the cameras view-projection matrix, like this I believe:

```
    Vec4 corners[8] = { Vec4(-1.0f, -1.0f, 1.0f, 1.0f), Vec4(-1.0f, -1.0f, -1.0f, 1.0f), Vec4(-1.0f, 1.0f, 1.0f, 1.0f), Vec4(-1.0f, 1.0f, -1.0f, 1.0f),
                        Vec4(1.0f, -1.0f, 1.0f, 1.0f), Vec4(1.0f, -1.0f, -1.0f, 1.0f), Vec4(1.0f, 1.0f, 1.0f, 1.0f), Vec4(1.0f, 1.0f, -1.0f, 1.0f) };
    const Mat4 inverseVPMatrix = glm::inverse(viewProjectionMatrix);
    for (uint32_t i = 0; i < 8; i++)
    {
        corners[i] = corners[i] * inverseVPMatrix;
        corners[i] /= corners[i].w;
    }
    float minX = corners[0].x, minY = corners[0].y, minZ = corners[0].z, maxX = corners[0].x, maxY = corners[0].y, maxZ = corners[0].z;
    for (uint32_t i = 0; i < 8; i++)
    {
        if (corners[i].x < minX)
            minX = corners[i].x;
        if (corners[i].x > maxX)
            maxX = corners[i].x;
        if (corners[i].y < minY)
            minY = corners[i].y;
        if (corners[i].y > maxY)
            maxY = corners[i].y;
        if (corners[i].z < minZ)
            minZ = corners[i].z;
        if (corners[i].z > maxZ)
            maxZ = corners[i].z;
    }

```

And the result would be the bounding box? But the resulting corners are all maybe at most \[-3.0, 3.0\], waaay too small.

The view/projection are calculated like this. The view/projection matrices have been working fine so far, so I do not believe the problem lies there, but still.

```
const Mat4 viewMatrix = camera.GetCameraTransform();
const Mat4 perspectiveMatrix = glm::perspective(mWindow.GetFOV(), mWindow.GetScreenWidth() / (float)mWindow.GetScreenHeight(), mRenderer->GetZNear(), mRenderer->GetZFar());

Mat4 Camera::Orientation() const
{
    Quaternion rotation;
    rotation = glm::angleAxis(mVerticalAngle, Vec3(1.0f, 0.0f, 0.0f));
    rotation = rotation * glm::angleAxis(mHorizontalAngle, Vec3(0.0f, 1.0f, 0.0f));

    return glm::toMat4(rotation);
}

Mat4 Camera::GetCameraTransform() const
{
    return Orientation() * glm::translate(Mat4(1.0f), -mTranslation);
}

```

Any pointers on what is wrong?

EDIT1: Camera standing at `Vec3(0.0f, 3.0f, 0.0f)`, looking down -Z axis generates the following inverted viewPerspective matrix:

```
Mat4(-1.24f, 0.0f,   0.0f,   0.0f,
     0.0f,   0.7f,   0.0f    0.0f,
     0.0f,  -15.0f,  0.0f   -5.0f,
     0.0f,   15.0f,  -1,0f   5.0f)

```

I dont know if that helps?

# Answer
> 2 votes
The answer was simple.

The order of multiplication was wrong - this is what it should've been:

```
corners[i] = inverseVPMatrix * corners[i];

```

I thought the order of vector/matrix multiplication didnt matter, but I guess it did... with the above, it works fine.

Now that I think about it, glm math library is column-major, so maybe that is why?

---
Tags: opengl, shadow-mapping
---


# Question
Title: Scanning a 2D tile map and detecting regions?
I have access to all points/tiles on the map with top-right most point being (0,0). Simplest way to traverse the map would be using for loops, one nested within the other to traverse the x axis, and then y (going through rows). But to solve this problem, I would probably need to scan the map in a more intelligent fashion. The important thing to note is that I'm only able to check one tile at a time and see what type it is. So t.getCoordinates() would return something like (32,54) and t.senseTile() would return: WALL, ROAD, OFF\_MAP, etc.

I wanted to scan the entire map and divide it up into regions. The regions would be of two kinds: "open" and "paths". For open regions, I just want to fill the entire region until it starts hitting boundaries, walls/obstacles, etc and stop the fill when appropriate. A rule for an open space is that a player should be able to get from one edge to another edge taking any path, angle, etc without bumping into some wall/obstacle.

For paths, there's certain number of tiles a region is limited to, then a new region starts (see lightBlue and gray).

Also, the paths should have entrances/exists also stored and to which regions they connect to. For example, scanning through a map like this (see pic), these regions should be generated. Not sure which data structure to use to connect them, but maybe a tree/graph would look like this:

```
  Gray
    |
 LightBlue
    |
   Pink
    |
  Yellow
    |   \
   Red  Black

```

Edit: I think Dijkstra's search algorithm could be a good starting point although I've never implemented it before. That only solves a small part of the problem. It still doesn't solve how it's going to detect regions. Also, I'm afraid Dijkstra's would be too costly in terms of time/performance (both are extremely important).

# Answer
> 2 votes
I'm a bit skeptical whether the auto-detection of paths will work for any map. I've come up with a heuristic to find paths, but it will subdivide your yellow region into various regions.

A horizontal path is a line of land that is bordered by land north and south of it. It has water to the west and east. These water tiles may be bordered of at most one other water tile to the north and south. Bridges should not exceed a maximum length. Likewise for vertical paths.

Scan your map for paths and set the tiles to a path id. (They are then no longer considered "land".) Then scan the map again and flood-fill each tile of open land with region ids. This will give you something like this, paths are marked in reddish colours:

You can then derive a graph with regios as vertices and paths as edges.

You'll note that the heuristic for finding paths is not very sophisticated. There should be a path subdividing the pale yellown region west near the L-shaped water patch. There shouldn't be paths around the central square pool.

I think it is very hard to find a satifying algorithm that can account for such cases in general. Maybe you can have an aggressive path algorithm that creates too many paths and then find a way to join the regions according to another heuristic, but I doubt it.

I think that it is better to define the paths by hand and then just find the regions. Or you have to mark the original map with possible locations for paths.

---
Tags: algorithm, search, maps
---


# Question
Title: Shooting the bullet out of the gun instead of the camera, yet keeping it accurate with respect to the reticle
I'm working on a first person game, and I've ran into a problem. In my game, there's the player's gun being rendered, as well as a reticle in the center of the screen - like this:

First, Let's imagine there was no gun model being rendered. Then firing the bullet is easy - you just spawn the bullet exactly where the player's "eyes" are, and then use trig to calculate the velocity based on whatever direction the player is looking.

But now, when we add the gun model... we can't just spawn the bullet where the players eyes are, we have to spawn it at the tip of the gun (right?). So you do that, but then... how do you move the bullet in a way that it will hit wherever the reticle was pointing?

Keep in mind that the bullet in my game (it's actually a rocket, in this case) will be moving slow enough that its movement can be seen, so some workaround that would usually work if the bullet is too fast to be observed will not work. For example, if you didn't spawn it so it looks like it's coming out of the tip of the gun, the player would definitely notice that.

# Answer
> 20 votes
Shoot a ray from the camera through the center/reticle into the world. Find out where in the world it hits. Fire the bullet from the gun's muzzle at that point instead of straight out of the gun.

Bonus points for animating the hands and gun to point in that direction while aiming around so the bullet still looks like it's firing straight out of the muzzle instead of coming out at an angle.

If you do the animation you could just fire the bullet straight out of the muzzle always. Just do your best to have the gun pointing at the point the reticle is aiming at within reasonable limits. It's also helpful to have two reticles in a way that naturally both shows the center of the screen that the player is trying to aim at and the point that the gun is actually aiming at.

Or you can you show a single reticle that is where the gun will be aiming after finishing the animation and to fire the bullet at that direction rather than the place the gun is currently aiming in its animation. This way the reticle always showing what the player will actually hit but won't pretend that you can e.g. fire around a wall just because the camera sees something that the gun can't possibly do.

All of these have been used in real games. Which you prefer is going to depend on the style of game you're making, what trade-off between simulation and game you're aiming for, whether this is multiplayer or not, etc.

# Answer
> -1 votes
What about getting rid of the reticle? Then, the bullets could go in a straight line from the gun, just as in reality. Aiming down the sights would then mean more as you would align the target and the barrel of the gun (minus a few inches at the player model).

---
Tags: vector, first-person-shooter
---


# Question
Title: add a server to facebook game, realistic cost for indie dev?
is it feasable in term of cost for an indie developer to add a server for a farming game, to save progress (new buildings) and the friends of each user? I have read figures about `Farmville`, that were around millions of dollars to just save the data.

So, on `facebook` the number of users can grow a lot: is it realistic to create a game for facebook as an indie developer as almost all games on facebook uses a server to save progress or achievements?

EDIT: it would be a simple farming game where you add new items and they'll have to be stored on a server. If the game is free, let's say it is downloaded 1M times, what kind of budget should I be ready to pay from the very beginning?

# Answer
Yes, it is feasible, whether you choose to roll your own or use a third party application.

Making it yourself can give you valuable experience and understanding of the systems behind making even a fairly simple server and database work. For an asynchronous system it is completely realistic to run tens of thousands of players on one fairly inexpensive server host.

Using a ready solution on the other hand will probably be faster and more scalable, but may be fairly expensive, making it a questionable choice if the game does not monetize well.

I would suggest rolling your own first and learning the ropes, making sure that the game itself proves it's worth. Perhaps try out the service of choice on trial, and make your own code use similar structures so the interface won't be painful to convert if you decide you need more features or scale.
> 1 votes

---
Tags: server, facebook, costs
---


# Question
Title: XNA : Character walking on tiles and getting stuck
I develop games for my own pleasure and also to share experiences with my kids learning coding.

Lately I have been working on a classic retro platform game using XNA and Farseer.

One issue I am having is that my characters sometimes get stuck while walking on tiles. These tiles are blocks put next to each other. It seems that sometimes when reaching the edge of the next tile, character get stuck.

I have read several solutions over the internet:

* Make a weldjoint - did not fix my issue
* Use an edgeshape - haven't found out how to do this yet
* Make one big shape out of my several tiles (the background floor for example) - haven't found out how to do this yet

A video can be seen here. You'll see that I have sometime to jump in order to be able to move on, otherwise I simply get stuck. I also commented and shared my sources here.

For now, as a nasty trick, I create circle bodies rather than rectangles. It does reduce the issue but not completely and I feel this is an ugly workaround anyway.

Would any one be so kind as to point me in the right direction or provide me an example? I write in VB.NET but can adapt a C# example if needed.

# Answer
Answering myself, I finally decided to review the way I generate my tiles.

When I detect a continuous serie of tiles, i'll generate one big rectangle rather than a serie of small rectangles. It requires a bit of gymnastic but not that much and it pays off : my characted no longer get stuck on edge.

I would rather have used edgeshapes but dont have the skills yet.

A video of the result can be seen here : http://labalec.fr/erwan/?p=754 .
> 1 votes

# Answer
Depending on the system you use, you could tweak your collision detection to allow a small amount of leeway on corners. This could even be useful for making stairs, with your stair height being slightly less than your leeway.
> 0 votes

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


# Question
Title: What is a good approach for making a relationship between the HUD and Environment?
What is an elegant / common way to build a relationship between the game scene / environment / world and the HUD that usually sits on top of it? I have thought about this for a while, and though there are ways to accomplish this that are easy to implement, they always seem to expose too much unrelated information between the two, or end up being too coupled. An example of this that I have used in the past would be to simply pass reference from the HUD to the Environment and vice-versa (which is obviously not a good apporach for many reasons, especially when aiming for low coupling).

What I want to end up with is a clean, uncoupled way to do things like:

1. From the HUD; reference and manipulate objects within the environment, change the state of the Environment itself.
2. From the environment; update the HUD to reflect the current state of the environment.

Maybe passing reference between the two *is* the way to go about this, but I feel like there's some pattern that I am missing for this type of task. Any insights into past experience and implementations concerning this type of problem would be very helpful.

# Answer
> 2 votes
The game⟷HUD relationship can be pretty well-expressed using the Model-View-Controller (MVC) paradigm. The Model is the programming logic, and has no concept of user interaction. A View is a way of somehow communicating information from the Model to the user, while a Controller is used to let the user interact with the Model.

We can think of the game logic as the Model in this instance. Actually, many game architectures already use an approach similar to MVC. The rendering, sound, and input systems are usually decoupled from the physics and logic, and so it is easy to fit in the HUD as a combination of a View and Controller (in many games the HUD doesn't even need to be a Controller).

The implementation of an MVC architecture varies wildly. A simple game will likely have the Views directly read data from the Model and the Controller will call certain functions that the Model exposes. If your game uses a physics engine, it's likely that you'll have split up your game loop so that the physics and logic runs at a constant rate, while the input and rendering are synchronized with the monitor refresh rate. In this case, the Model will spit out game state snapshots which the View will read and interpolate between, and the Controller will queue up events into a buffer.

The advantage of using MVC is that your game engine is separated into two main decoupled areas. The Model is one, and it is isolated from the workings of the View and Controller. In many cases, the View and Controller overlap, such as with the HUD, so they are the second layer. It's usually fine for stuff like that to be coupled more tightly, as the Controller needs to know that you've actually clicked within some rectangle to build a unit, for example.

Incidentally, the View-Controller layer is the only one that should need to change if you are porting from one platform to another. The Model doesn't care whether you're playing on a PC, a Mac, a Playstation, or an iPhone. You can build different Views and Controllers to deal with different rendering libraries or input devices, and use them with the same Model.

---
Tags: actionscript-3
---