# Question
Title: Animating sprites at different speed than what the game runs at
I am building a Javascript/canvas platformer game, and it's coming along nicely. The only problem I've really run into where I can think of any solution at all is the animation of my player sprite.

The game loop is running every 16ms, which equates to 60fps. On every game loop, I'm using a method of my player class (called draw) to draw the player sprite. The sprite looks like this: https://i.stack.imgur.com/THlGX.png

On every call of the draw method, I am advancing the "frame" of the player sprite, to give the illusion that the player is moving. As far as I know, this is common practice. However, due to my draw method being run every 16ms with the game loop, my player sprite is animating extremely quickly, and it doesn't look realistic at all.

Is there a way to slow this down to a pre-defined speed, or will I have to resort to adding loads of duplicate frames to my player sprite? Obviously that's not a great solution, as to make it look realistic at a game speed of 60fps I'd need to have a LOT of frames.

Here's my relevant code:

```
// Sets off the main game loop
setInterval("gameLoop()", gameSpeed);

function gameLoop() {
    // Updates
    player.update();

    // Draw
    c.clearRect(0, 0, canvas.width, canvas.height);
    player.draw();
}

// Then in my player class...

this.draw = function() {
        if(this.state == "idle") {
            c.drawImage(this.idleSprite, this.idleSprite.frameWidth * this.idleSprite.frameCount, 0, this.idleSprite.frameWidth, this.idleSprite.frameHeight, this.xpos, this.ypos, this.idleSprite.frameWidth, this.idleSprite.frameHeight);
            if(this.idleSprite.frameCount < this.idleSprite.frames - 1) { this.idleSprite.frameCount++; } else { this.idleSprite.frameCount = 0; }
        } else if(this.state == "running") {
            var height = 0;
            if(this.facing == "left") { height = 37; }
            c.drawImage(this.runningSprite, this.runningSprite.frameWidth * this.runningSprite.frameCount, height, this.runningSprite.frameWidth, this.runningSprite.frameHeight, this.xpos, this.ypos, this.runningSprite.frameWidth, this.runningSprite.frameHeight);
            if(this.runningSprite.frameCount < this.runningSprite.frames - 1) { this.runningSprite.frameCount++; } else { this.runningSprite.frameCount = 0; }
        }
    }

```

# Answer
What I always do in this case is store a `frameTime` variable and store the last update time variable inside my animation class. Then I only update the frame if the `currentTime - lastUpdateTime > frameTime`, in which case I also set last update time to `currentTime`.

Huzzah for animation =\]
> 10 votes

# Answer
I'd try to use a new timer for the player, just a timeout for the next animation and in case of bad things the gameloop can clear this timer and reset the player.
> -1 votes

---
Tags: javascript, html-canvas, platformer
---


# Question
Title: How to make sure there's always a walkable path for enemies in a tower-defense game?
I am making a 2D tower defense game. So far I have a 2d array which acts as a grid for my game. I'm able to place towers on it, run enemies and some dragging and tower firing stuff.

Now I am facing a problem in tower placement logic. I want that there's always a walkable path for enemies, meaning that the user should not be able to block the way completely by placing towers. Eg. if the user places towers vertically on a map, the algorithm must prevent the placement of a tower that will complete the vertical line. Or in any other way there must be at least one free (walkable) space so that the enemy can escape.

My current logic checks in all directions whenever tower has placed. If there is a tower upwards it calls the same function again on that upper tower until it hits a wall. It returns 1 for upward wall and 5 for downward wall and returns function(up/down tower) if there is a tower. here is the code:

```
int checkCollision(tower)
{
    if( there is a  tower up)
    return checkCollision(up tower);

    if(there is a tower down)
    return checkCollision(down tower);

            ......all directions.....

    if( there is a wall on UP )
        return 1;

    if( there is a wall DOWN )
        return 5;

        ....all walls......

    return 0;
}

```

Now what I want is, simultaneously check if there is a northern wall and southern wall **or** check any other directions with any other possibility (like up-down, up-diagonal, down diagonal... and so on) to not let the user place a tower as there should be one place left for enemy.

I am unhappy with my code at the moment. I mean my code tells me that a wall is found but how can I check that a wall is found in one direction and a wall also found in another direction? I dont want to go into possibilities like:

```
if(checkCollision(tower) == 1 && checkCollision(tower) == 5)
  "You cannot place"

```

I want something like:

```
    if( any combination of more than 2 wall found and there is entry/exit point in between)  //so it is wall to wall
    "You cant place"

```

I have also tried pre-calculating flags if there are walls on two sides (like up-down, up-diagonal etc.) then don't let the user place the tower but that still doesn't work.

# Answer
> 23 votes
Wouldn't it be simpler to use a pathfinding algorithm to check whether the AI still has a clear route? Presumably you use one already to make the enemies navigate from the entrance to the exit, so just run it with the tower added, and if it fails then the tower isn't allowed.

# Answer
> 3 votes
I assume you already have some code (using something like the A\* algorithm) for the enemies to find a path to their destination. Every time the player tries to place a tower, you can just put a temporary obstacle where the tower would be and run the pathfinding code to check that there will still be a path for the enemies.

You can optimize this in various ways. For example, if the newly placed tower only touches at most one existing obstacle, it cannot block the path. You can also save the results of previous checks (at least until something changes), so that if the player tries the same location several times, you don't have to re-check it every time.

Also there are some techniques that only work in some cases. For example:

* If the possible locations of towers don't overlap, you can use a bridge-finding algorithm to find exactly which locations will block the path of the enemies.
* If the playing field is two-dimensional, there's a clever trick based on the fact that there exists a clear path from the left side to the right if and only if there does not exist a continuous wall from the top to the bottom. Thus, you can label each tower (or other obstacle) depending on which, if any, side of the playing field it is connected to by a wall.

Maintaining these labels as new towers are added is easy and quick. If a new tower would link two sides together, it would block the path of the enemies. Of course, if a tower is removed, you still have to recalculate the labels, but you only need to do that when a tower is *actually* destroyed, rather than every time the player merely hovers the cursor over a potential location for a new tower.

# Answer
> 1 votes
I agree with SimonW that you should just run your pathing algorithm. For completeness, here is a trick used by Starcraft/Warcraft TD maps, which do not have a way to check if the pathing algorithm passes/fails.

Let's say enemies can come anywhere from the top of the buildable area, and have to move to anywhere below the buildable area; and there are walls to the left/right. Do a flood-fill of all towers touching the left-wall. If any towers found touch the right-wall, the path is blocked.

# Answer
> 0 votes
it should be more like

```
bool checkCollision(tower)
{
if(there is tower above)
  return checkCollision(tower above);
if(there is tower below)
  return checkCollision(tower below);
...
...
...
if(wall above)
  return 1;
if(wall below)
  return 5;
...
...
...
return 0;
}

```

then later in your code where you want to check whether to allow placing the tower or not:

```
if(!checkCollision(tower above) && !checkCollision(tower below) && !checkCollision(tower left)...[check all sides]...)
  //You can place the tower
else
  //You cannot place the tower

```

Also, change your algorithm to add the ability to return the coordinates of which tile of wall was found adjacent to the string of towers. Checking whether the same wall tile was returned and discarding that would allow you to go through loops of towers as well.

By loop of tower I mean (don't mind my ascii art):

```
--------------------------
|                        |
|   TT                   |
|TTTTTTTTT               |
|       X T              |
|       T                |
|                        |
En                       Ex
|                        |
|                        |
|                        |
|________________________|

```

It would not let you place a tower at X. The tower above, the tower on diagonals, the tower on the right and the tower below all will report wall collisions, however the coordinate of the wall tile will be the same. This is what you need to screen out as well.

# Answer
> 0 votes
Easy, I just built my first path finding program today, it took me a little over 2 hours and apart from declaring variables, it's only 27 lines of code including closing brackets.

program in your pathfinder an array for all your real walls, and an array for all your hipothetical walls, if a player wants to make a tower on a space, then the space selected is a hypothetical wall; Run your pathfinder to include hypothetical walls, if the program comes back with a path found then the tower can be built, if not then the tower isn't allowed to be built.

Cheers

Here's my code,

```
function PathFind(){

var keepgoing:Number=1;
var count:Number=1;
var smallcount:Number=0;
var keepgoing2:Boolean=false;
var startX:Array=[];
var startY:Array=[];
startX[0]=new Array();
startX[1]=new Array();
startY[0]=new Array();
startY[1]=new Array();
startX[0][1] = disc.loca;
startY[0][1] = disc.locb;
startX[1][1] = String(disc.loca)+"$";
startY[1][1] = String(disc.locb)+"$";

for(var c:Number=1; c<=keepgoing; c++){
    smallcount=0;
    for (var a:Number=1; a<=3; a++){
        for (var b:Number=1; b<=3; b++){
            if (a==2 || b==2){
                if(Space[startX[0][c]+(a-2)][startY[0][c]+(b-2)].valid==true && SpaceII[startX[0][c]+(a-2)][startY[0][c]+(b-2)]==true){
                    count++;
                    smallcount++;
                    SpaceII[startX[0][c]+(a-2)][startY[0][c]+(b-2)]=false;
                    startX[0][count]=Space[startX[0][c]+(a-2)][startY[0][c]+(b-2)].IDx;
                    startY[0][count]=Space[startX[0][c]+(a-2)][startY[0][c]+(b-2)].IDy;
                    startX[1][count]=startX[1][c]+String(Space[startX[0][c]+(a-2)][startY[0][c]+(b-2)].IDx)+"$";
                    startY[1][count]=startY[1][c]+String(Space[startX[0][c]+(a-2)][startY[0][c]+(b-2)].IDy)+"$";
                    if(Space[startX[0][c]+(a-2)][startY[0][c]+(b-2)].goal==true){
                        keepgoing2=true;
                        disc.stringA = startX[1][count].toString();
                        disc.stringB = startY[1][count].toString();
                        //thisText.text=startX[1][count] + "%" + startY[1][count] + "*";
                        success=true;
                    }
                }
            }
        }
    }
    if(keepgoing2==true){
        c = keepgoing;
    } else {
        keepgoing = keepgoing + smallcount;
    }
}

```

}

Basically, my code will create an array of paring X & Y strings, Then my moving units inherit the first successful pairing strings, and then they just disect the strings one segment at a time. Each coordinate is broken with a "$".

And the beautiful thing about the above code is that 'keepgoing' will only ever get as big as the grid size, and becomes more efficient with the more towers that are placed, it's efficiency being maximized when there is only one set path.

If you need any help with what I've got above here for you just let me know.

---
Tags: c#, unity, tower-defense
---


# Question
Title: Why is OpenGL using 100% CPU shortly after start up when wglSwapIntervalEXT is enabled?
I have a game which uses SFML, which in turn uses OpenGL.

When I run the game, it will use 100% CPU for (usually) about 24 seconds, and then immediately falls down to normal usage. I can't figure out what's going on during these 24 seconds. In some cases, it stays at 100% CPU usage forever, but it usually stops after 24 seconds.

I've attempted to profile it, but the most information I can get is that the time is all being spent in my OpenGL driver. Aside from this, I can't see any useful information. It's also unable to tell me who the caller of the offending OpenGL code is; instead, it just tells me that the caller is an 'Unknown Frame' called by main.

One interesting thing I've noticed is that although it's using 100% CPU, it has no negative effect on my game. It runs without any FPS loss or slow down. This makes me think that the problem may be in the code that's enforcing vsync.

Has anyone encountered this? Any ideas what it might be, or how I can go about figuring it out?

Also, to clarify, the game is single-threaded. The thread using 100% CPU is my game thread, not one of the background threads created by OpenGL.

**EDIT :** The problem is, in fact, vsync. It's enforced using OpenGL's `wglSwapIntervalEXT` function. If I disable it and use sleeps to limit my frame rate, CPU usage stays low. I still don't understand why it's behaving like this when vsync is enabled, though.

# Answer
> 1 votes
It's probably the same issue as a DirectX. DirectX (and probably OpenGL) sit in a tight spin wait until the screen is ready to sync - this is probably to guarantee that the draw happens at the very next available sync.

You have figured out how to work around it yourself; but I found the following works better (you can still get tearing with your current code) - it reduced my CPU usage to 30% on an empty render loop.

```
set end = time for vsync after the next
while (time not within 10% before vsync and time < end)
   yield thread
end
perform present/wait for swap

```

Also you must NOT use `Sleep()` (unless you pass 0, which yields the thread) as it only has a resolution of ~15ms-30ms; which isn't nearly good enough for this. Use a high performance counter.

The basic idea is that we try to get within a certain range of the vsync - but and leave the rest up to DirectX/OpenGL. However, we don't sit around forever and wait - because we could miss it continually (we are yielding the thread after all); so rather give up at a certain point and let DirectX/OpenGL go into its tight loop.

You will also find more solutions described here.

# Answer
> 1 votes
More than likely, the driver does not want the CPU to run too many frames ahead of the CPU, so it waits for the GPU to complete it's current frame, before continuing to process the next draw instruction. Ideally, it would wait for some sort of interrupt and put the thread to sleep, but it sounds like it is just spinning on your config, and is likely polling the hardware or some piece of device mapped memory in a tight loop.

The more you render, the less time you will have to wait on the CPU - if you maintain the CPU having a short lead (using sleeps as you did - not that I recommend it unless you are trying to optimize power), the CPU won't have to wait for the GPU to catch up. This could explain the variable results you are seeing.

Also, compiling shaders may be another reason for high CPU usage on startup, but this is unlikely to go away by disabling vsync.

---
Tags: opengl, windows, vsync
---


# Question
Title: Interpolating from Current- to Target-value every frame
I have a CurrentValue and a TargetValue. Every frame, i want the CurrentValue to "lerp" towards the TargetValue.

I always seem to get jitter, because the currentvalue never perfectly hits the targetvalue. Lets say i have a targetvalue of 5 and a currentvalue of 4, and the speed is 2. Then the value will go from 4 -\> 6 -\> 4 -\> 6

I have been looking at the Lerp function, but i just don't see how exactly i can use it.

The practical applications im thinking of is accelleration of a car, turning a turret on a tank etc. What are some best practices on doing the above?

Thanks in advance :)

# Answer
> 5 votes
In general, `lerp` functions don't take a *speed*, they take a *parametric representation* of how much they should be in between your start (A) and end (B) parameters.

Of course, if you have a constant speed, you can figure out how long it should take you to go from A to B doing some simple math. If you're moving at X m/s, and you need to travel Y m, then you can get time by doing Y / X (if you can't remember this, just remember your units and solve for seconds).

Now in your code you have a time amount, a start position, and an end position. You're also going to have to keep track of elapsed time to give you your parametric (0..1) value to pass into your lerp function.

So if this is in a `Tick` function somewhere:

```
currentMovementTime += deltaTime;
var t = currentMovementTime / totalCalculatedTime;
var currentPosition = Lerp( startPosition, endPosition, t );

```

One common thing to do is that if your current elapsed time is greater than your total calculated time, just clamp it (so your t is 1). That way you'll calculate your end position to be the actual end position you want to be at.

All that being said, your particular examples aren't terribly suited for lerping. For rotating a turret you probably just want to apply a constant rotational velocity while the user has a button held down. Likewise for acceleration. Generally speaking lerping is only really useful for things that you know take a fixed amount of time and aren't dependent on continuous user input.

# Answer
> 2 votes
Compute two separate values:

* `delta`, the difference between your current value and your expected value; in your case, `4 - 5`, ie. `-1`.
* `step`, the amount to change wrt. your speed, in your case `2 * Δt` where `Δt` is your timestep (you appear to have a constant timestep `Δt = 1`, but if you want to cope with framerate jitter, you should consider adapting)

If `abs(delta) < step` it means you reached the target; set `currentvalue = targetvalue`.

Otherwise, set `currentvalue += step * sign(delta)`.

# Answer
> 1 votes
A lerp function is something like this:

```
 NewCurrentValue = SourceValue + (TargetValue - SourceValue) * Ratio;

```

Many times I choose a constant ratio, and work over current value, this way I have not to consider time duration and time elapsed, and results are fine.

```
 CurrentValue = CurrentValue + (TargetValue - CurrentValue) * 0.01f;

```

---
Tags: xna, interpolation
---


# Question
Title: Why do games for Facebook have to be about 622 pixels high?
I am wondering, why do games for Facebook have to be about 622 pixels high?

# Answer
> 11 votes
Think about the general user base. A lot of players will own laptops that are about 768px high (most common around the 15.6" range of screens) so making it about 622px means that game will fit on the screen.

There are some games that have a fluid canvas which resizes the game area to fit the browser window which is quite nice.

---
Tags: flash, facebook
---


title: How to achieve realistic fake physics?

text:
# Question
Title: How to achieve realistic fake physics?
In my opinion, games that are most entertaining to watch and play implement fake physics, the difficult issue is how to implement the fake physics and still allow it to appear realistic. Most popular car driving games implement this really well.

**Question** Anyone has any tips or know of anywhere I can learn more about how these are implemented?

---

**Long Story** For example, Need For Speed is entertaining when the player car crashes into the computer car, but it would not be fun if we land off the track each time the player collide. In the game, it is obvious that some game logic is in place to steer or land the player car upright, face correct direction and on track most of the time even after a massive collisions. The game instead causes the computer car to suffer heavier damages like flying of the screen after many spins etc to enhance effects.

As another example, suppose at a time instance, a speeding player car is driving at the close rear left of a computer car and real physics dictates in the next time instance the player will definitely bump into the computer and lose speed and control. Then at this point, the player could steer right to avoid the car, or steer left to bump into its rear. In an entertaining game, we may still want the player to avoid the front car completely if he steers away and experience an exciting near miss.

In NFS, this experience appears to be implmented in a few ways such as player auto-steer avoidance, scraping pass and rebound to right of computer, computer car steer away to avoid, computer gets hit but lose control and spin off track to give way to player.

On the other hand, it the player steers to engage in a collision, we want to add excitement to spin the computer very badly but still keep the player on track with a good speed.

In NFS, these fake collisions and steering are not easily noticeable as they feel very realistic even though if we study them closely, it looks almost like the are scripted. One method I have tried is to determine the final state of collision and then compute the path backwards. But this only ensures the car is in a desired final state, does not address the realism.

# Answer
> 5 votes
You probably want to start with reasonably realistic (if simplified) physics and make modifications from there. The first modification you'll likely make will be using something called damping. This is essentially adding extra friction to selected interactions and velocity components. The second modification is detecting states that aren't recoverable (i.e. being overturned) and *adding* small velocity components.

The basic idea is that you calculate the real forces and resulting velocity changes, apply them and then quickly dissipate the components that don't line up with the direction of predefined "friendly" velocities. This will include things like velocity components that are perpendicular to the ground (these will make your car bounce out of control) and to a lesser extent components that are perpendicular to the intended direction of travel (these will make you crash into the wall).

For the second modification you want to be able to detect those states that are "not fun" (like being upside-down) and giving a little nudge in the right direction. You can also achieve this by having a lower bound on the rotational velocity component whose axis is the length of the car under some circumstances (like the aforementioned overturned state).

Overall I'd suggest that this sort of thing is an art. The more time you spend trying to make it both natural and fun, the more you'll like it. Some experimentation is going to be required. These tips will hopefully get you started.

# Answer
> -2 votes
You could use a physics engine. Box2D is popular: http://box2d.org/ and free

Otherwise google around. Bullet, Havok, etc

---
Tags: physics, user-experience
---


# Question
Title: Which pathfinding algorithm should I use for multiple enemies and tower placement?
I am new to game development and I am developing my first "Tower Defense"-type game.

I need a pathfinding algorithm to place my towers and to move enemies.

* For tower placement case: I want the algorithm to run from entry to exit so that if it passes, the user can place tower and if fails user can't.
* For the enemy case: it should help multiple enemies to find their shortest path by running it for each enemy's current position to exit.

Searching about path finding I have found some algorithms like Floyd–Warshall, A\*, Breadth First, Dijkstra's and some others. Some answers give priority to Floyd's over it for path finding with multiple enemies. So what do you suggest that I use for my case?

My grid size is 17x23 and my game would have multiple entry and exit points in future. I am using the Unity game engine and scripting in C#.

# Answer
I recommend using A\* for it's simplicity. You have a relatively small grid, and I presume monsters can only move in cardinal (up, down, left, right) directions.

I have an implementation of A\* working in Objective-C (C# should translate OK) on my developer's blog here. You can see the monsters currently interacting with a changing landscape on my first post. A\* post is lower down...

I'll add some extra comments to your questions on 1) & especially 2).

**Don't run a pathfinding algorithm for every monster.**

Run the pathfinding algorithm **once** for each entrance & exit pair, and put each monster on that path. Then, for each monster that is not on that path, run a pathfinding algorithm.

This will greatly improve performance, because it makes some assumptions about the general use case of the path - the monsters will already be following a valid path, whcih has now just changed in one place. Chances are, one new path will suffice.

If it doesn't (say the new object placement brakes the monster group into 2). Then start with the monster that isn't on the new valid path that is farthest away from the exit. That path, should be valid for every monster in the second group (who are not on the first path).

Hope that makes sense. In a very simple grid-style map system where users can place objects only 1-at-a-time, you really don't need to run a path for every monster. Especially if they're not interacting in real-time with anything else. (i.e. field changes in a static manner, you're not pathfinding two groups of monsters against each other).

HTH
> 5 votes

# Answer
I'm actually fixing to implement the same type of thing for an AI semester project. I'm wanting to have a tower defense game that starts out with an open field to the tower. I want to be able to place objects on the field to alter the path of the creeps.

So, a creep will be on a certain path and I'll be able to place something that blocks them in the middle of the path. They will then be able to find a new path.

What I'll be using is Incremental A\*. This allow you to re-use parts of the path( tree ) that are the same, so you don't have to re-run the full A\* algorithm.

Here's a link. http://books.nips.cc/papers/files/nips14/CN09.pdf
> 0 votes

---
Tags: c#, unity, path-finding, tower-defense
---


# Question
Title: How do I organize my class structure for networking?
In my gameclient I have the following classes(compontents): Game, GameScreen, GameWorld, Player.

They are structured like this: Game has two GameScreens: MenuScreen and MainScreen. MenuScreen has an instance of GameWorld. GameWorld has an instance of Player.

Now I wanted to add a multiplayer mode to my game. For this I have a class "NetworkConnection". For the problem keep in mind that this class needs to access individual objects in the game world, as well as vice-versa. Meaning that individual objects (as a simple example the player) need to send messages to the class. It could look like this for example:

```
networkConnection.SendPlayerPositionUpdate(x, y, playerID);

```
* The problem

Where do I put my NetworkConnection?

I thought about adding it to "Game" because it is a part of the game (duh). But when I want the player to tell its position to the server I have to do this:

```
(Inside the player class)
world.screen.game.networkConnection.SendPositionUpdate(...);

```

The otherway around (when messages are being received from the server)

```
(Inside the network class)
game.currentScreen.world.player.SetHealthPoints(receivedHealth);

```

Where should I place NetworkConnection? Should I make NetworkConnection a global singelton ?

# Answer
If you are using a language with both Reflection and Eventing like C# or Java, you can use a combination of the two to achieve some decoupling between the game and the network. I wrote about how I implemented this in C# at length here: http://jcpmcdonald.com/index.php/80-blog/91-networking All of the code is open-source too if you want/need to look.

**To summarize**: Your game entities (like your player) will have events that will communicate changes of state to anyone or anything that cares to listen (locally). These events are for things like moving, health changes, death, and any other game-related events you may have. Each of these events will have its own EventArgs class that it uses. Hidden inside the EventArgs, I have coded all of the information to reflectively replicate this event on an other client (read the linked article to see).

Now for the fun part. When an entity is created, my networking class looks at the entity through reflection and starts listening to all of the events that need to be replicated over the network. When one of these events is triggered, the network class picks it up, unwraps the reflection information that I have placed in the event, then send that off to the interested party(s). On the receiving side, I open the packet, read the reflection information, and invoke the method.

Using this method, my network knows as little as possible about the game, and the game knows almost nothing about the network.
> 4 votes

# Answer
You could have PlayerNetworkComponent extending NetworkComponent and a NetworkManager singleton that has a GameWorld and list of NetworkComponents. Then in your game loop, you'd call Update() on your NetworkManager. You'd register a PlayerNetworkComponent where you create your Player.

In NetworkManager.Update(), you'd call NetworkComponent.Update() on all of your components, and then in PlayerNetworkComponent, you might get the NetworkConnection for the PlayerNetworkComponent and use that to send the Player information.

This would fit nicely into a component-based architecture.
> 2 votes

---
Tags: networking, data-structure
---


# Question
Title: How do I set up moving platforms in a 2D side scroller to interact with the player properly?
Edit: I changed the way that gravity was applied so that it is applied even when a player is standing on a block, so instead of the game outputting that you are stepping on a tile as true and false (because if it is true gravity isn't applied, and it is moved out of collision thus in the next frame it does not collide) so now I'll be easier to check if the player is still colliding with a moving tile. I think that I will make a bool that checks if the player was colliding with the tile in the last frame, and if so set the velocities to equal that of the tile plus whatever they are doing (jumping, gravity, walking left and right).

I am trying to create moving tiles such as the ones in basically any platformer. The game is a 2d sidescroller, and the problem that I am running into is handling standing on moving tiles.

The tiles are stored in a vector, but I am unsure how to make it so that the play will have the same y and x velocity as the tile they are standing on, as well as not fall off it.

I was thinking of creating a pointer to the tile they are colliding with on the top (that is standing on it) and setting the velocities to be equal to that plus whatever the player presses (so going left or right or jumping).

However, I am unsure how to check if they collide and how to check if the player had jumped off the tile. I know how to check if the player's collision is at the top using half widths and half heights, but beyond that is a mystery.

# Answer
I think you are having trouble because you might have confused yourself for world coordinates with camera coordinates.

In a simple 2D game, the player is always in the 0,0 (center) camera view (assume no camera easing), but the world coordinate keeps changing.

When the scene/background/hit-map moves, you can think of it as a camera position offset. However, everything on the map is still the same position relative to the world coordinates.

So when you do hit collision, just use world coordintates. Don't try to do hit collision in camera coordinates, at least not conceptually, and unless it is a mouse click collision test. Or your brain will explode!

And if your chracter changes world position, just apply the character world position offset to the scene's camera view offset.

**EDIT**: For moving tiles, you can "tag" the character to the tile when he lands, and "de-tag" it when he is in the jumping state. On each animation frame, change the position of the tile by an offset and for each tagged object, change their position by the same offset. Since at the beginning of each frame snapshots are static, just do bounding box collision test like normal.

This "tagging" is that same idea as you would equip a 3D character RPG with armor and weapons.

To handle the case where player simply walks off the edge: while the character is tagged to a tile, check if character x coord is outside or inside tile min and max x-coord to see if it is still on the tile. De-tag or re-tag to another tile as necessary.

imo, we want to make the game run as efficient as possible and do away with unecessary computations. so I would not think the gravity idea is the best. gravity only needs to be applied when character is in mid-air. Can easily use the chracter jump and land events to turn gravity on and off
> 2 votes

# Answer
Your idea to pass a pointer is the right way. If a collision occurs between two objects pass a pointer to each. Then each object can decide how to alter the properties of the coliding one. Try to differ between objects by attaching a property (like PLAYER, OBSTACLE, POWERUP) to handle collisions with different types in other ways.

For checking collisions the easiest way is to use libraries. At least just look at the docs to get some ideas how to implement collision detection in your own way. For Example http://clanlib.org/wiki/MainDocs:Collision\_Detection.
> 0 votes

# Answer
Hahah, this is a pretty common problem, here's what I do-\>

**Step 1:** collision detection: Be sure you're separating your map into sections or using quadtrees to speed up grouping,

**Step 2:** basic collision resolution, my preferred method works great for moving platforms, I always preform this check

```
if (myPreviousBottom <= theirPreviousTop){ //bottom side collision
  //move upwards outside of range of other block
  //add their velocity to our position (THIS is what you want to implement)

  //I also have a quick method that's overloaded in other classes called_bottom collide()
  //and another method of sending events between objects, I send an event notifying
    //the other object of the collision here
}
if (myPreviousTop >= theirPreviousBottom){
  //simply move our position outside of theirs
}

//CHECK FOR COLLISIONS AGAIN
if (collide(us,them)){

  if (myPreviousRight <= theirPreviousLeft) { //we have a right hand collision
   //check to see if we should slip by the platform
   //move object in question to the position of the other object - our object's size
  }

   //repeat for left side
}

```

The important step here is when you have a bottom collision you add the other object's velocity to your position. This allows you to move about freely on their platform and have your own physics unaffected by it's (you may want to, instead, change your axis velocity to theirs and add their other axis's position to the object in question)
> 0 votes

# Answer
There are several ways to deal with this situation. One way is, whenever the player is standing on something (a platform, a monster's back, etc.), to work (conceptually) in **a reference frame moving along with whatever the player is standing on**. So, as far as the player's movement is considered, the platform they're standing on isn't moving — the rest of the world is.

Of course, this means you need to keep track of what (if anything) the player is standing on. It also means that whenever this changes, e.g. because the player jumps, falls off or steps from a moving platform to a stationary one (or vice versa), you need to change reference frames; depending on your implementation, this typically means e.g. adding the previous platform's velocity to that of the player when they jump off it.

One convenient feature of this method is that you don't need to worry about gravity except when the player is airborne. In fact, you can make jump physics and walking physics as different as you like, which is often useful in games — the approximations that work well for (semi)ballistic motion in mid-air are not the same as those which work when you're in contact with a solid immobile surface.

Conversely, one thing that *may* be a problem with this approach is if the platform your player is standing on undergoes rapid acceleration. (Think of a spring-loaded platform that launches the player into the air like a catapult.) In that case, you may need to include extra checks to see if the player should fly off or slide along the platform (or fall over, if you model that kind of stuff).

(In principle, the player should be tossed off if the downward acceleration of the platform they're standing on exceeds gravity, and should slide if the sideways acceleration exceeds the total downforce (sum of upward acceleration and gravity) times the coefficient of friction. Of course, many games essentially assume infinite sliding friction and otherwise neglect most effects of horizontal acceleration. In particular, if your platform moves horizontally and suddenly reverses direction, that *should* cause anyone standing on it to stumble — but I've never seen a game actually do that.)
> 0 votes

# Answer
This can be a bit tedious to do in raw C++. Are you using any libraries, if so what are they?

My personal suggestion would be to use a 2d physics engine called Box2D.
> -1 votes

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


# Question
Title: Searching for the right engine for a simple FPS
With some holiday time coming up I thought it might be interesting to look to try and make a game that's been in my mind for a while now.

I'm a professional programmer so I have experience with most common languages (and I am not scared of picking up a new one if needed) but I've never done any graphics or game work before.

Basically what I'm after is an engine or toolset that will allow me to create a simple FPS (based around interaction with world objects, not physic based, just buttons) while hopefully avoiding as much graphics code as possible (don't get me wrong, I'm willing to learn it, I just don't want to spend my nights writing a lighting engine ;) ), so that I can spend my time on logic and concept.

tl;dr **I'm looking for suggestions (and if available tutorials) of a simple engine to make a simple FPS on**

I might be wrong but it seems that something like UDK might be graphics overkill, I'm happy for this to be ugly as hell.

As always, any help pointing me in the right direction would be amazing. Thanks!

# Answer
> 5 votes
If you can wrap your head around Unity, it should do exactly what you want. It's built around an entity system, which can be hard to grasp if you're not used to them (they aren't really compatible with object oriented programming, which can be a hard habit to give up), but it will handle all the graphics for you. It will also handle asset importing/exporting, physics, and a host of other things. Oh, and it's free. You can program in JavaScript or C#, and there are lots of plugins available to do things like animation and pathfinding.

It comes with an example FPS project that you can build on as well. In fact, that would be the main thing I'd look for in whatever engine you decide to use - it's much easier when you have a running game to alter than a blank screen.

# Answer
> 2 votes
I would recommend writing a mod for either Unreal Tournament or Half-Life 2. They both have great communities, and great tools. Unreal uses their own well designed scripting language, while Half-Life 2 uses C++. In either game, you should be able to make your own weapons and intractable objects without having to deal with all of the lighting, bump-mapping, sky-boxes, networking, controls, UI and whatever else goes on in a 3D engine. The disadvantage to making a mod is that anyone who wants to play it has to own the game you modded.

# Answer
> 1 votes
I would suggest using UDK.

Here's a great series of tutorials I found on Youtube:

http://www.youtube.com/watch?v=K7AAgQHJWGc&list=PL649C1907D32B01C8&index=1&feature=plpp\_video

I hope this leads you in the right direction :)

# Answer
> 1 votes
I'm going to go against the grain. You need the minimum required set to get to prototyping the gameplay you desire. In that vein, I'm going to suggest Ogre3D. If you're familiar with C++ then you should be able to jump in with few worries. Documentation is great and building a simple 3D environment should be as quick as following a few tutorials.

Using anything else will provide multiple layers of knowledge that you'll have to attain before actually getting to build a simple simulation.

# Answer
> 1 votes
Horde3D is really simple. You can get a simple game up and running within a few hours. Ogre3D is another great choice.

---
Tags: first-person-shooter
---


# Question
Title: Why large builder classes rather than separate clases in component-based entity systems?
I was reading about component-based entity systems and I was wondering why there is usually a large EntityBuilder class with methods like `CreatePlayer()`, `CreateEnemySpaceship()`, and `CreatePowerup()`, all creating an entity, attaching some components, and returning the entity.

The class has the potential to get quite large given enough different entities and having to search this large code-file can eventually become quite cumbersome. Also, with this system, since all entities are of type Entity, to determine *what* something actually is, you would have to add some sort of TypeComponent to the entity which may contain a string like "Player", "Enemy", and "Powerup". Now you lose some benefits of strong typing and have to rely on personal memory more (bad in my opinion).

Another problem with this setup is the inability to use function overloads based on what type the entity is. Instead one would have to use hashtables based on some identifying component which is a bit ugly.

I was wondering, instead of having these large builder classes and cumbersome ways of determining what an entity really is, why not just have separate classes for each entity? Well, that is what we *were* doing but they resulted in large and complex hierarchies, right? Well, I'm not advocating large hierarchies. Rather, move every method from this monolithic builder class to a separate class deriving from Entity and place that code in the constructor. No multiple-inheritance. No large trees. Example: Both Ship, Spaceship, and EnemySpaceship would all derive from Entity and only Entity.

This could be useful for determining the types of entities when a collision occurs and how to proceed with handling the event. The classes themselves would basically be empty except for the constructor logic in how to construct the entity (attaching components and whatnot). This solution seems to be a lot more extendable as well, considering if one would ever need to modify the creation process of an EnemyEliteFighterSpaceship, rather than searching through some large builder class, just go to that class file.

Am I missing something here? I suppose, if all else, my real question would be of an elegant way to determine *what* an entity is when it collides with another entity so some action could be taken (increase score, play sound, etc.). I initially tried setting up some sort of TypeComponent but it just seems a bit hackish as opposed to simply deriving from the base Entity class. Also, deriving from a base entity class gives strong-typing and type-safety support, gets rid of the public static builder class, and allows for polymorphic behavior and ease of determining an entity's type.

So I'm wondering, with all these positives and no perceivable negatives (other than .. more files? organization trumps file count in my opinion), why do most component systems favor these large builder/factory classes rather than my proposed approach?

# Answer
You seem to have a couple of questions here so I will try and give a few answers.

```
IComponent
{
    int iObjectId = MyUniqueObjectThatImAPartOf;
}

```

Every component should know by some unique id which object/entity it is a part of. I am not an advocate of using an Entity class to bind the pieces together. I do however know that people do do it that way. I honestly thing OOP is just such a line of thought for developers that its hard to get rid of them. The best argument I ever heard was the first one I ever heard however. If you have a central object you always wonder what should be in a component and what should be in the central object. Just avoiding having to ask that question all the time and come up with an answer was good enough of a reason for me to give up the 'Entity' object and link all components together by an ID.

Remember to not think like a player in this instance. If you are a player you are looking on the screen and seeing an object that represents your player. On the display you can see how much health you have, how close to the lava you are, and that big giant rock about to smack you in the head. But to the game engine, to show your character it doesn't care what your health is, if that lava is close enough to cause you damage or strain or that the rock is now hitting you. For rendering a character all it needs is the mesh and texture data, positional information.. things specifically for rendering.

The reason not to have separate classes for each entity is that you get alot of over lap of code.. Everything is like to have collision and health and a graphical representation and an action for it to go off and do, etc. The ways to solve having to write that over and over again is to either have trees to inherit functionality from or component systems so you can reuse the sub sections to build a larger object. I personally go with component simply because of ease of maintenance and update. I have been in the situation too many times where complex and ever growing inheritance trees make things annoying to deal with. (Might also be why I can let go of the Entity so easily.)

The large builder class is like going back two steps, before there was inheritance at all so it all had to be in the giant FactoryThatMakesMeObjects class so I would have to say Really stay away from them. Having a PhysicsComponentFactory makes sense to me, something that deals with creating, maintain and updating all the physic components for the game.

I am a bit confused as to why, in C#, a simple GetType() is not giving you enough Run Time Type Information. If you were using C++ then I would suggest using a template that would create a static pointer to RTTI for the templated parameter.. It would give you a nice static pointer uniquely identifying it as that type, great for comparison and going up the tree to see if you are a child for some base type.. but I would think the very nicely done internal reflection capabilities of C# would solve that for you.

Taking RTTI into a component system and you should also be ideally keeping like components within their own groups. So you are not mixing the component that tracks what an object uses to render itself with the object that tracks its health, its gear, its physics.. any bound AI to the object, a motion object.. etc.. They may all be linked together by an ID but they have nothing else to do with each other so should not be in the same list.. there should never be a need for a large LinkedList\_AllTheComponentsInMyGame.. But a LinkedList\_PhysicsComponents, LinkedList\_RenderableComponents and so on.

All else failing, in a component system here is a potential way that you could determine what an entity is when it collides with another entity so some action can be taken.

```
PhysicsComponentManager
{
    // I make the assumption that the manager that contains the physics components
    //  that check for collisions with each other (Bounding Volumes) also contains
    //  the components that handle collisions with other objects.
    CheckForCollisions()
    {
        // If Comp1 has collided with Comp2
        foreach(IBoundingComponent Comp1 in AllBoundingComponents)
        {
            foreach(IBoundingComponent Comp2 in AllBoundingComponents)
            {
                if (Comp1.CollidesWith(Comp2))
                {
                    // Let Comp1 know of the collision
                    NotifyObjectOfCollision(Comp1.ObjectId, Comp2.ObjectId);
                    // Let Comp2 know of the collision
                    NotifyObjectOfCollision(Comp2.ObjectId, Comp1.ObjectId);
                    // Probably mark Comp1 and Comp2 as collision resolved for this
                    //  frame so we dont do this twice or the like.. or just let the
                    //  physics system do its thing if you have one.
                }
            }
        }
    }

    NotifyObjectOfCollision(ObjectId, CollidedWithObjectId)
    {
        ICollideable Comp = FindCollideable(ObjectId);
        if (Comp == null)
            return;
        Comp.DoCollision(CollidedWithObjectId);
    }
}

```

Hope this helps, I know its rather long but a good detailed question deserves a good amount of detail in the answer. (And please take the code as suggestions, no way are they optimal!! Just meant to show the flow :))
> 1 votes

# Answer
2. Read this answer on composition over inheritance.
3. Use one single method to create different entities, this leads to more maintainable code since *configuration-specifics belong in external data files, not in code.* So avoid `createPlayer()`, `createEnemyOne()`, `createAsteroid()`, in favour of `createEntity(int id, string type, PhysicsComponent physics, SpriteComponent sprite, ...)` with parameters being either primitives or complex objects themselves, and collectively specifying a unique object such as an asteroid.
4. Use the builder pattern specifically because you need a class dedicated to translating said configuration data into concrete entities, while maintaining separation of concerns between classes (e.g. your game class "Main" should not be constructing entities, but it should be delegating the task to another class).
5. Read this answer on collision detection and entity destruction.
> 3 votes

# Answer
> Rather, move every method from this monolithic builder class to a separate class deriving from Entity and place that code in the constructor. No multiple-inheritance. No large trees. Example: Both Ship, Spaceship, and EnemySpaceship would all derive from Entity and only Entity.

You're trying to accomplish two things with this design.

1) Determine the "type" of an entity.
2) Separate out some code that constructs entities out of some "monolithic builder class".

Comment on point #1:

I'm going to frame my context within how Unity handles component based design, as that's how I'm most familiar with it.

In their parlance, you have `GameObject` (which is analagous to `Entity` in your example, I would imagine) which, basically, just contains `Components`. You derive from `Component` (specifically a subtype of Component, but that's unimportant). Nothing derives from GameObject.

When a collision occurs (because you have game objects with some kind of physics components attached), the engine sends a message to every component on those game objects that such a collision occurred along with some appropriate variables.

If you need to determine what course of action you can do a couple of things.

1) Check the name of the game object and do some logic. This is probably a bad approach.

2) Check the tags on the game object you collided with. The component that handles that for the player could check to see if they collided with something that's a friend or a foe. This is an okay approach, but limiting.

3) Check to see if the game object collided with has a specific type of component attached, and then do appropriate things. So the player component could see if the thing it collided with has a component of type `PowerUp`, get that instance of that component, then do something with it. This is probably the most powerful approach.

Either way, from the way you're describing it, having things that derive from your `Entity` class in a component-based system is kind of missing the point.

On #2:

It seems like a method that constructs a "Enemy Space ship" can just be a helper function somewhere else. It probably doesn't even need to be inside a class, depending on how your engine is set up with globals. You can just as easily separate them out in multiple files without doing something like setting up yet another inheritance tree.

Also, it's worth noting that Unity data drives game object construction, generally. Implementing a system that lets you design an entity in an editor will reduce some of this monolithic code you have an issue with.
> 0 votes

---
Tags: xna, c#, game-design, architecture, component-based
---


# Question
Title: How do I manage textures in memory in OpenGL?
I'm writing a game engine which is going very fine. However, I'm now posed with handling textures.

My Engine is in 2D, for simplicity reasons mostly to get a good idea of how to work with OpenGL. I do this in C++, and I have a hierarchical set-up when it comes to classes. There's a base class and some other classes derive from that.

So now I'm onto the part where I want to load up some textures and apply them to polygons. The way my engine works in drawing things is like this:

1. Load up a tile map file and parse it. The tile map contains all the information like events, lights, passability. All very interesting, not. Except the part where it loads a tileset, as defined by the map.
2. The parser realises the map uses a tileset, which is stored in **resources/tilesets/dungeon\_interior\_cave1.xml**, which contains all the information on what textures are used.
3. It loads the textures as said by the tileset-XML-file, it gives them an ID and then the SceneManager-class knows how to lay out the tiles and what texture to slap onto each of them. Once this is done, it tosses the instance of the SceneManager to the OpenGL renderer.

This might not be the best explanation of how my engine works, but simply put:

1. *SceneManager* loads the file **resources/maps/dungeon3Interor.msf** (msf being a custom map format (MSF stands for **M** age **S** cene **F** ile ). The MSF file refers to a tilset.
2. *SceneManager* loads the tile set at **resources/tilesets/dungeon\_interior\_cave1.mts**.
3. *SceneManager* loads up all the textures from **resources/textures/\< path\_to\_textures \>**
4. *SceneManager* tosses itself to the OpenGL render, and OpenGL renders the whole thing.

I think that's the best I can do at explaining. Know that the SceneManager itself contains no OpenGL code, just paths and information that OpenGL needs to know to render the scene.

What I'm interested in, what is the best practice to handle this, and how to handle OpenGL texture storage. I understand OpenGL keeps the textures in it's texture memory, and that I have to use glGenTextures to allocate a texture and that I then swap betwe--.. I actually have no clue.

What's a good way to keep track of all the textures you loaded into the memory and switch between them in C++, preferably using a class or a set of classes to accomplish this.

# Answer
> 4 votes
Well, in general working with textures consists of a few steps:

```
glGenTextures(1, &texID);             // Get memory for texture
glBindTexture(GL_TEXTURE_2D, texID);  // Tell OpenGL you are using this texture
// Set its properties:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// Set its data
glTexImage2D(GL_TEXTURE_2D, 0, 4, sizeX, sizeY, 0, GL_BGRA, GL_UNSIGNED_BYTE, img);

```

`texID` for example can be a member variable of the class, so each object of the class holds one texture. (Side note: In copy constructor, you actually have to generate another texture, use `glGetTexImage(GL_TEXTURE_2D, 0, GL_BGRA, GL_UNSIGNED_BYTE, other_img);` to get the image and copy it to the other texture).

Then on use, you have to have `GL_TEXTURE_2D` enabled (by `glEnable(GL_TEXTURE_2D);` and the texture bound by:

```
glBindTexture(GL_TEXTURE_2D, texID);

```

and when you want each vertex of your polygon bound to any point, you call:

```
glTexCoord2f(tex_x, tex_y);

```

Note: These stuff are legacy OpenGL though (for example OpenGL v1.2). If you are using new OpenGLs, such as OpenGL 4, I don't really know.

Anyway, if you want to see a texture handled by a class, you can check out the texture part of my raster graphics library: header and source

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


title: 3D motorcycle models for web 3D tools

text:
# Question
Title: 3D motorcycle models for web 3D tools
I'm developing a website that can display 3D models of motorbike. I haven't decided on which tool to use yet but it seems most of them support X3D and VRML files. So I'm searching for already-made models in either format but got no result so far, anyone know where I can find one? Thank you.

# Answer
> 2 votes
**Turbosquid.com** has quite a lot of free mesh models of moterbikes, you can browse them **here**. If they are not available in your desired formats, you can always download them and convert them through one of many converters available out there, such as **MeshLab**, which supports both VRML and X3D, among many other formats.

---
Tags: 3d, models, web
---


# Question
Title: Minecraft-style player-gound collision detection
The title pretty much says it all... (Minecraft is a game consisting of evenly-spaced cubes for terrain, like voxels)
Note: I am using C# XNA.

I am pretty sure AABB is the way to go, yet I don't know how to implement it. I admit, I'm almost looking for code, but theories/ideas are ***very*** welcome.

Important capabilities of my code: I have a function that can get a block anywhere in the world, and get a BoundingBox for that cube. Hence, I have created a BoundingBox for the player to collide with those cubes. My idea was to get the blocks around the player (maybe 4x6x4) and test against those.

The problems I have been having: Say the world is a flat plane. If I use the method of go the shortest distance out, then if the player is slightly clipped into the ground (from gravity), but even slighter into the next block over, then the player will be pushed sideways (and so cannot walk along ground). Of course, this is assuming I react to every block intersected. Another problem is knowing which direction to go (aka negative x or positive). That takes me to my final problem- Getting the amount of intersection, in the correct direction (+ or -) has been tough for me.

I hope I haven't been too hard to understand, I'm not too good at explaining things... And if this question has already been asked, I'm sorry, I looked for it... for 3 days straight.
One last thing, if someone knows exactly how minecraft does it, or has source (I know MC modders have the source, how else would they mod), please point me to it.

# Answer
> 3 votes
This is my 2D AABB approach to the solution. It should translate easily into 3D, simply by adding the Z axis. Replace "Left" and "Right" with "West" and "East", add "North" and "South", and keep "Up" and "Down". "West" and "East" would be X, "North" and "South" would be Y, and "Up" and "Down" should then be Z.

What I do is pick all the tiles that intersect with the entity based on size, and then keep it as tile start and end positions. After that, I construct two lists of tiles based on direction, holding only solid tiles. The corner is kept separate, to avoid the list having the same point twice which would be the corner.

I then iterate the list of solid tiles, and then fix velocity according if we intersect with the tile in the next position.

The corner is a special case in my engine, rather than increase the steps, I just rule you always land on top.

Feel free to ask questions, though I'd encourage you to try and rewrite it for your own engine, to get a better grasp on what the function is doing.

```
...
    private Vector2 ApplyTileCollision(Vector2 velocity)
    {
        Vector2 nextPosition = this.position + velocity;

        Int32 startx = (Int32)(((Single)position.X) / Tile.SIZE) - 1;
        Int32 endx = (Int32)(((Single)position.X + this.Width - 0.0001f) / Tile.SIZE) + 1; // because of float imprecision, we subtract 0.0001f.
        Int32 starty = (Int32)(((Single)position.Y) / Tile.SIZE) - 1;
        Int32 endy = (Int32)(((Single)position.Y + this.Height - 0.0001f) / Tile.SIZE) + 1; // because of float imprecision, we subtract 0.0001f.

        // these variables are filled with only solid tiles
        List<Point> horizontalWall = new List<Point>();
        List<Point> verticalWall = new List<Point>();
        Point ?corner = null;

        if (this.IsMovingRight)
        {
            // we use starty + 1 to remove the corner
            for (Int32 y = starty + 1; y < endy; y += 1)
                if (realm.GetTile(endx, y).IsSolid)
                    verticalWall.Add(new Point(endx, y));
        }
        else if (this.IsMovingLeft)
        {
            // we use starty + 1 to remove the corner
            for (Int32 y = starty + 1; y < endy; y += 1)
                if (realm.GetTile(startx, y).IsSolid)
                    verticalWall.Add(new Point(startx, y));
        }

        if (this.IsMovingDown)
        {
            // we use startx + 1 to remove the corner
            for (Int32 x = startx + 1; x < endx; x += 1)
                if (realm.GetTile(x, endy).IsSolid)
                    horizontalWall.Add(new Point(x, endy));
        }
        else if (this.IsMovingUp)
        {
            // we use startx + 1 to remove the corner
            for (Int32 x = startx + 1; x < endx; x += 1)
                if (realm.GetTile(x, starty).IsSolid)
                    horizontalWall.Add(new Point(x, starty));
        }

        if (this.IsMovingLeft && this.IsMovingUp)
        {
            if (realm.GetTile(startx, starty).IsSolid)
                corner = new Point(startx, starty);
        }
        else if (this.IsMovingRight && this.IsMovingUp)
        {
            if (realm.GetTile(endx, starty).IsSolid)
                corner = new Point(endx, starty);
        }
        else if (this.IsMovingLeft && this.IsMovingDown)
        {
            if (realm.GetTile(startx, endy).IsSolid)
                corner = new Point(startx, endy);
        }
        else if (this.IsMovingRight && this.IsMovingDown)
        {
            if (realm.GetTile(endx, endy).IsSolid)
                corner = new Point(endx, endy);
        }

        foreach (Point point in verticalWall)
        {
            // if our next position would collide with the tile, we fix velocity.
            if (nextPosition.X + this.Width > point.X * Tile.SIZE &&
                nextPosition.X < point.X * Tile.SIZE + Tile.SIZE)
            {
                if (this.IsMovingRight)
                {
                    velocity.X = point.X * Tile.SIZE - (position.X + this.Width);
                }
                else if (this.IsMovingLeft)
                {
                    velocity.X = (point.X * Tile.SIZE + Tile.SIZE) - position.X;
                }
            }
        }

        foreach (Point point in horizontalWall)
        {
            // if our next position would collide with the tile, we fix velocity.
            if (nextPosition.Y + this.Height > point.Y * Tile.SIZE &&
                nextPosition.Y < point.Y * Tile.SIZE + Tile.SIZE)
            {
                if (this.IsMovingDown)
                {
                    velocity.Y = point.Y * Tile.SIZE - (position.Y + this.Height);
                }
                else if (this.IsMovingUp)
                {
                    velocity.Y = (point.Y * Tile.SIZE + Tile.SIZE) - position.Y;
                }
            }
        }

        // in case we only have a corner to consider, we rule that we land on top of it, or hit the bottom of it.
        if (corner.HasValue && verticalWall.Count == 0 && horizontalWall.Count == 0)
        {
            // if our next position would collide with the tile, we fix velocity.
            if (nextPosition.Y + this.Height > corner.Value.Y * Tile.SIZE &&
                nextPosition.Y < corner.Value.Y * Tile.SIZE + Tile.SIZE &&
                nextPosition.X + this.Width > corner.Value.X * Tile.SIZE &&
                nextPosition.X < corner.Value.X * Tile.SIZE + Tile.SIZE)
            {
                if (this.IsMovingDown)
                {
                    velocity.Y = corner.Value.Y * Tile.SIZE - (position.Y + this.Height);
                }
                else if (this.IsMovingUp)
                {
                    velocity.Y = (corner.Value.Y * Tile.SIZE + Tile.SIZE) - position.Y;
                }
            }
        }

        return velocity;
    }
...

```

---
Tags: xna, collision-detection, minecraft-modding
---


title: Rotate entity to match current velocity

text:
# Question
Title: Rotate entity to match current velocity
I have an entity in 2D space moving around, lerping between waypoints. I would like to make the entity rotate around its own origin to face the current direction that it is going, I.E. towards the next waypoint in the list.

In case the waypoint movement code is needed, I'm using the following (this is contained inside of the entity that is following the waypoints) :

```
    private void GoToWaypoint() {
        if (waypointList.Count > 0) {
            Vector2 origin = helper.GetOrigin(position, width, height);
            int nodeWidth = 50;
            int nodeHeight = 50;

            if (moveToPosition != waypointList[0]) {
                moveToPosition = waypointList[0];
                moveToPositionOrigin = helper.GetOrigin(moveToPosition, nodeWidth, nodeHeight);
                distanceToPosition = moveToPositionOrigin - origin;
            }

            if ((Math.Ceiling(distanceToPosition.X) < 0)) {
                position.X -= moveSpeed;
                distanceToPosition.X = (int)Math.Round(distanceToPosition.X + moveSpeed);
            }
            else if ((Math.Floor(distanceToPosition.X) > 0)) {
                position.X += moveSpeed;
                distanceToPosition.X = (int)Math.Round(distanceToPosition.X - moveSpeed);
            }

            if (Math.Ceiling(distanceToPosition.Y) < 0) {
                // Check if the entity moves below the top boundary
                if (position.Y > 0) {
                    position.Y -= moveSpeed;
                    distanceToPosition.Y = (int)Math.Round(distanceToPosition.Y + moveSpeed);
                }
                else {
                    distanceToPosition.Y = 0;
                }
            }
            else if (Math.Floor(distanceToPosition.Y) > 0) {
                // Check if the entity moves below the bottom boundary
                if (position.Y < 550) {
                    position.Y += moveSpeed;
                    distanceToPosition.Y = (int)Math.Round(distanceToPosition.Y - moveSpeed);
                }
                else {
                    distanceToPosition.Y = 0;
                }
            }

            // If the entity gets in the waypoint, or the distance to the waypoint is 0 on both axis (which can occur due to screen boundaries)
            if ((helper.InNode(position, moveToPosition, width, height, nodeWidth, nodeHeight)) || ((distanceToPosition.X == 0) && (distanceToPosition.Y == 0))) {
                waypointList.RemoveAt(0);
            }
        }
    }

```

I know this may have been asked elsewhere, and the bit of searching that I did on this type of problem, didn't really help me. I'm slightly math retarded, so I don't understand the explanations that don't really explain what the math is exactly achieving. So any help that breaks down the math and functions needed to achieve this would be greatly appreciated.

Thanks.

# Answer
**Step 1:** Ensure that your sprites have a *consistent* default orientation. That is, all your sprites need to point in the same direction. This will make everything else vastly easier.

**Step 2:** Given two waypoints, you can compute the vector direction between them. Normalize this vector. This is the direction that you want your ship to face.

**Step 3:** The C-standard library function `atan2` computes an angle (in radians) from a normalized vector. The vector (1, 0) will produce an angle of 0.

Therefore, you can compute the angle to rotate the sprite by calling `atan2(dir.y, dir.x)` (note that Y comes *first*. That's not a typo).

**Step 4:** In Step 1, we ensured that all sprites have a default orientation. `atan2` has a default orientation of (1, 0). Therefore, we need to adjust the angle we got, so that providing a vector in the direction of the default produces a 0 angle. This adjustment is done by applying an offset to the value from `atan2`, depending on what the default orientation is (note: the following assumes that +Y is up and +X is right). The offset for each default orientation is:

* right: 0
* up: -pi/2
* left: -pi
* down: -3pi/2

**Step 5:** When you draw this sprite, use the appropriate XNA function to rotate the sprite at draw time. I'm sure XNA has a way to do that. You may have to convert the angle to degrees though.

Note that this computation also assumes that the XNA rotation function rotates counter-clockwise, such that positive angle values rotate it counter-clockwise.

---

Advice: You should not have a "moveSpeed" that is added to both X and Y. You should have a `moveSpeed` which is multiplied by the normalized direction to the destination waypoint. That vector (which is the velocity vector) is then added to the current position to get the new position.
> 5 votes

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


# Question
Title: How can I modify how my scene is drawn to make it look like it's taking place at different times of day?
My game has a day-time association with the scene, that the morning light will be different from the afternoon and the night. But I don't know how to make this difference.

Here is an example in Pokemon game:

I have an idea that put a layer on the top of the game with the transparency about 10 - 20%, and change its color depends on the time, but I don't know which color is good.

Are there any other mechanisms to do some kind of day/night cycle in a game of this style?

# Answer
> 10 votes
There are two ways to do this. The easy way and the way that will actually look like it's dark.

The easy way is exactly what you said: throw down a full-screen quad that darkens the scene. But:

> I have an idea that put a layer on the top of the game with the transparency about 10 - 20%, and change its color depends on the time, but I don't know which color is good.

That's because there is no "good". There are only varying levels of bad. It will always look like what it clearly is: a bright scene that has been darkened. Real nighttime is not simply a bright scene that has been darkened. Different areas are darker in different ways.

The best you can do is run a bunch of tests and find the color that is least offensive. Nobody can give you a "good color", because such a thing does not exist. There is only "what you personally can tolerate for your particular scene".

The *right* way to do this is to have your artists redraw all the sprites for a darker scene. Obviously this is labor intensive, which is why most sprite-based games don't have day-night cycles.

Indeed, sprite games that did do some night-time scenes also had the advantage of using paletted sprites. In those cases, they simply created a special "night" palette for the sprites. This gave them the opportunity to tweak the colors for the best visual effect.

You could try something similar to this, but it would require you to use paletted sprites yourself.

# Answer
> 2 votes
> I have an idea that put a layer on the top of the game with the transparency about 10 - 20%, and change its color depends on the time, but I don't know which color is good.

Trial and error is a *great* thing. You've got the idea of it - an overlay of some sort would be the easiest. The suggestion to use orange for dusk, and black for night, is also a good one. But nobody here can tell you what colors to use to make your game look good - that's entirely up to you and your sense of design.

A much more complicated way to change the time of day is to generate an entirely new set of sprites for each period of the day. Most of these sprites would be simply shaded differently, as if you were using the above overlay, but this would allow other effects like streetlights and such.

# Answer
> 1 votes
From my very limited experience doing this type of thing in a couple games that I've done, to make it "darker", i.e. night time, I would do just like you said and add a black layer over the game, and make it closer to transparent than opaque.

For evening time, I would do the same thing, but with an orange color to give it a "dusk-y" feel.

If you want to make it get darker (or orange-er) gradually, then just gradually raise the opacity on the color over time.

That's what I would do anyway. I'm sure there may be a better way out there.

---
Tags: graphics, graphic-effects, effects, graphics-design
---


# Question
Title: What has changed in the lighting systems of Rage, Battlefield 3 to make them so realistic?
I've played and completed Rage and currently Battlefield 3 (which looks a lot better with less hype). One thing that is immediately apparent is the lighting, or the bump maps - I can't figure out which it is - makes the experience on a high end PC a lot clearer and better looking.

What is the advancement that these games are making use of in Open-GL/Direct-X or the graphics cards that has increased the realism of the lighting engines so dramatically?

# Answer
> 7 votes
As Tetrad suggested, I'm adding my comment as answer: You can find some useful info about BF3 here: The Secrets Behind Battlefield 3 and Frostbite 2

# Answer
> 3 votes
One of the major contributors to realistic-looking lighting is linear-color-space lighting, HDR, and filmic tonemapping, which have become a lot more widespread in the last few years. Another is the use of physically-based shading models.

# Answer
> -2 votes
Video cards with programmable pipelines using high level shader languages allow developers to pull off just about any effect they want including realistic lighting, shadow mapping and soft shadows, bump/normal maps, post processing, and much more.

Some Info: https://cs.senecac.on.ca/~gam670/pages/content/shadr.html

---
Tags: lighting
---


# Question
Title: Why do objects interpenetrate in this simple collision solver?
The code below is from a Microsoft XNA sample here. This is quite a simple rigid body simulation that ignores many physical effects (such as angular momentum), but it does try to push objects (spheres) apart so that they are not penetrating one-another.

However, the simulation allows spheres not only to penetrate, but when many spheres are stacked on top of each other, small spheres can be almost completely inside of larger spheres. If I make all spheres have the same radius and mass, then the simulation performs reasonably well (with minimal interpenetration).

Can someone explain why there is any interpenetration at all? Since it moves the positions of the spheres, it seems like interpenetration should be impossible.

For each sphere in the simulation, this method is called on every other sphere.

```
/// <summary>
// Given 2 spheres with velocity, mass and size, evaluate whether
// a collision occured, and if so, excatly where, and move sphere 2
// at the contact point with sphere 1, and generate new velocities.
/// </summary>
private void SphereCollisionImplicit(Sphere sphere1, Sphere sphere2)
{
    const float K_ELASTIC = 0.75f;

    Vector3 relativepos = sphere2.Position - sphere1.Position;
    float distance = relativepos.Length();
    float radii = sphere1.Radius + sphere2.Radius;
    if (distance >= radii)
    {
        return; // No collision
    }

    // Add epsilon to avoid NaN.
    distance += 0.000001f;

    Vector3 relativeUnit = relativepos * (1.0f / distance);
    Vector3 penetration = relativeUnit * (radii - distance);

    // Adjust the spheres' relative positions
    float mass1 = sphere1.Mass;
    float mass2 = sphere2.Mass;

    float m_inv = 1.0f / (mass1 + mass2);
    float weight1 = mass1 * m_inv; // relative weight of sphere 1
    float weight2 = mass2 * m_inv; // relative weight of sphere 2. w1+w2==1.0

    sphere1.Position -= weight2 * penetration;
    sphere2.Position += weight1 * penetration;

    // Adjust the objects’ relative velocities, if they are
    // moving toward each other.
    //
    // Note that we're assuming no friction, or equivalently, no angular momentum.
    //
    // velocityTotal = velocity of v2 in v1 stationary ref. frame
    // get reference frame of common center of mass
    Vector3 velocity1 = sphere1.Velocity;
    Vector3 velocity2 = sphere2.Velocity;

    Vector3 velocityTotal = velocity1 * weight1 + velocity2 * weight2;
    Vector3 i2 = (velocity2 - velocityTotal) * mass2;
    if (Vector3.Dot(i2, relativeUnit) < 0)
    {
        // i1+i2 == 0, approx
        Vector3 di = Vector3.Dot(i2, relativeUnit) * relativeUnit;
        i2 -= di * (K_ELASTIC + 1);
        sphere1.Velocity = (-i2) / mass1 + velocityTotal;
        sphere2.Velocity = i2 / mass2 + velocityTotal;
    }
}

```

In particular, I though that this:

```
sphere1.Position -= weight2 * penetration;
sphere2.Position += weight1 * penetration;

```

Should completely disallow any interpenetration, why doesn't it?

# Answer
> 5 votes
I think your problem comes from multiple collisions.

Consider three spheres A, B & C.

A sits there.

B hits A. Fine.

C hits B. B is nudged into A. Oops.

# Answer
> 5 votes
This code is taking the collision between two spheres and moving them based on their masses and velocity.

Here's a really basic illustration to show why there is penetration between a blue ball and a green wall.

In this example the center of the ball is 5 feet from the edge of the wall. The ball is moving at 1 foot per second and you are running at a framerate of 1 frame per second. At frame 4 there is no penetration, but frame 5 will have penetration. There's no way of knowing that frame 5 will collide so you can't just say stop when it gets to the wall. Instead you check every frame if the ball is partially inside the wall. If it is, move it back by the amount of penetration and apply the reflective velocity. This is how most collision detection algorithms work. The alternative is to check each frame how far you are from colliding in a certain direction. The problem with that is you need to know what direction to check. This would not work in your situation so the route you are taking is the right one.

The drawback of this approach is the jitteriness that you are probably experiencing. When this script tells a ball to move based on the last collision, then it may be moving to penetrate into another ball, which will then send the ball back to collide with the first. Making it jump back and forth. You can modify the mass of the objects to help with this. That will cause them to jump back slightly less drastically, or reduce the speed in which they collide in the first place.

# Answer
> 5 votes
You should read up on Speculative Contacts for catching when collisions will happen before you end up with this kind of penetration.

# Answer
> 1 votes
SphereCollisionImplicit() gets called after the spheres have moved. That movement could have ended up with collision & interpenetration, this method resolves that.

start frame:

1. elsewhere in your code, the position is updated by velocity.
2. Then this method is called to see if that resulted in collision/penetration.
3. if so, it separates them & reflects/changes their velocities.
4. next frame, positions are updated with new/changed velocity... goto 1.

# Answer
> 1 votes
There is interpenetration because every time a ball's position and velocity is changed, it needs to be checked to see if it has collided with any other ball that was checked earlier in the loop. For instance, given 3 balls:

Start 1. Ball #A is checked against Ball #B, no collision

1. Ball #A is checked against Ball #C, no collision
2. Ball #B is checked against Ball #A, no collision
3. Ball #B is checked against Ball #C, found collision!! Ball #B and #C are moved.
4. Ball #C is checked against Ball #A, no collision
5. Ball #C is checked against Ball #B, no collision

Done

So... Step 2 may have moved Ball #B into Ball #A, causing interpenetration.

To fix, I think whenever a ball is moved, it needs to be re-checked against all the other balls, whenever it is moved. In this scenario, Ball #B bumps into Ball #C, richocheting Ball #B into Ball #A, richocheting Ball #A into Ball #C!, which hits Ball #B again....

How many richochets do you process in one frame? Do you also need to re-check against all the walls after each richochet also?

Start 1. Ball #A is checked against Ball #B, no collision

1. Ball #A is checked against Ball #C, no collision
2. Ball #B is checked against Ball #A, no collision
3. Ball #B is checked against Ball #C, found collision!! Ball #B and #C are moved.
4. Restart #B and #C loop...
5. Ball #B is checked against Ball #A, found collision!! Ball #B and #A are moved
6. Restart #B and #A loop...
7. Ball #A is checked against Ball #B, no collision
8. Ball #A is checked against Ball #C, found collision!! Ball #A and #C are moved
9. Restart #A and #C loop
10. Ball #A is checked against Ball #B, no collision
11. Ball #A is checked against Ball #C, no collision
12. Ball #B is checked against Ball #A, no collision
13. Ball #B is checked against Ball #C, found collision!! Ball #B and #C are moved
14. Restart #B and #C loop
15. Ball #B is checked against Ball #A, no collision
16. Ball #B is checked against Ball #C, no collision
17. Ball #C is checked against Ball #A, no collision
18. Ball #C is checked against Ball #B, no collision Done

---
Tags: xna, c#, physics, rigid-body-dynamics
---


title: Brick Breaker Game Structure

text:
# Question
Title: Brick Breaker Game Structure
I am working on a brick breaker style game (i.e., like Arkanoid) in C#/XNA. As I add more features such as powerups, special brick types, etc I am running into problems figuring out how the whole game should be structured. For instance, I have a static CollisionManager class that my ball objects call each update to check if they are hitting something like a brick. While this works, it also puts the ball object in charge of updating other objects (such as letting the Brick know it has been hit, or some other game function not directly related to the ball).

Every powerup or feature I add keeps forcing me to re-evaluate how everything is pieced together. Are there any types of standard layouts I could use to help minimize problems like this? I like the idea of having my CollisionManager just manage collisions, and my ball objects just managing stuff related to the ball, and bricks managing brick stuff; however, some cases require updating multiple things. This leaves me trying to figure out just which part of my app I should put in charge of the dirty work of handling these specialized tasks.

# Answer
I think it's a good design to encapsulate functionality within a given class. The *ball* knows about ball-related stuff, while bricks mind the brick-related business...

Your problems seems to be how these components communicate and how you can easily add new features. The best way (architecture-wise) is to have very generic components that are as loosely coupled as possible. A good architecture would be components.

For a simple game like Breakout, a component based architecture might be overkill. Instead, you could do something like this:

**Game:** (or Level?) keeps track of all entities and performs the `update` method on all of them.

**CollisionManager:** Detects collisions and notifies bodies/entities that were part of the collision. You could do this by implementing a messaging system or by invoking a method like `handleCollision` on the entities.

**Ball:** has velocity and direction and updates its position. For greater flexibility, you could make the Ball a state-machine, so you could easily implement different behaviors as different states. This could come in handy for behaviors of power-ups.

**Brick:** Could also be implemented using a state-machine to implement different brick-states.

Probably the biggest gain for your game would be some kind of messaging. The Brick could send a message when it gets destroyed (eg. hit by the ball). The *score-manager* could listen to that message and update the score accordingly. The message could also trigger a power-up to appear randomly etc.

The benefit of having a messaging-system (or a similar pattern like "signal and slots" or the observer-pattern) is that you can have loosely coupled components that communicate with each other. So you can easily add more components later on by having them listen to messages and perform some tasks. Imagine you got the messaging system in place as described above and your Brick sends out a message when it gets destroyed. Listeners will make sure the score is being updated and there's a random chance that a power-up will appear. Now you could simply add another listener for that message that will play a special sound whenever that brick gets destroyed...
> 8 votes

# Answer
If your collision manager is managing collision, then that means it has access to your bricks and your ball(s). So shouldn't your collision manager be managing collision and updating your ball(s) and also the bricks that it hit?

If that is the case then your collision manager would need to be passed the bricks that the ball could possibly hit.

I would create a helper function that would split the screen into quadrants. This helper function can then detect what quadrant the ball(s) is in and then check against the list of bricks and detect which ones are within the same quadrant. If any are in the same quadrant as the ball, I would then put all of those bricks into a new list, and pass that into the collision manager and do the collision checks on those. (Make sure to pass the list as a `ref` so any changes done on any bricks passed in gets reflected on the original brick).

That should take away the updating responsibility from the ball.

As for a general structure, I like to contain everything within a GameManager. So this game manager would contain the ball manager and brick manager. I would make the collision manager a singleton. That way you don't have to ensure that every other manager or class has an instance of the collision manager within it.

So the game manager would call the ball and brick managers update methods and within those updates, collision checks would also be done.

Hope that helps. Good luck.
Cheers.
> 3 votes

---
Tags: architecture
---


# Question
Title: How do I design a game framework for fast reaction to user input?
I've played some games at cca 30 fps and some of them had low reaction time - cca 0.1sec. I hadn't knew why.

Now when I'm designing my framework for crossplatform game, I know why. Probably they've been preparing new frame during rendering the previous.

```
RENDER  1 | RENDER  2 | RENDER  3 | RENDER  4
PREPARE 2 | PREPARE 3 | PREPARE 4 | PREPARE 5

```

I see first frame when second frame is being rendered and third frame being prepared. If I react in that time to 1st frame it will result in forth frame. So it takes `3/FPS` seconds to appear results. In 30 fps it would be 100ms, what is quite bad.

So i'm wondering what should I design my framework to response to user interaction quickly?

# Answer
For an in-depth study of latency in games, Mick West is the undisputed master. Read these two articles first, and it will make everything else make so much more sense.

There are two aspects to this. The first, which you've picked up on, is the latency between an instantaneous control input (e.g. a button press), and the time at which the user perceives the effects of that action. The firing of a gun is usually the best example of this as it's easy to measure. There are many contributing factors to this, most of which are completely out of your control. Worse, it's a cumulative effect, so if each stage is introducing a bit of latency, it can all mount up to lead to severe overall latency. Different types of latency you'll see:

* display latency (how long between a frame being presented at the input and the pixels on the screen changing to reflect that frame)
* GPU /sync latency (how long between you calling Present and the input being presented to the display, usually tied to framerate, e.g. at 30fps there may be anywhere from 0-32ms between calling Present and the next VSync where the GPU output would change)
* buffering latency (you've pointed this one out - frames prepared based on the world state from previous frames because rendering takes so long it's more efficient to have the rendering being done while the next frame is being prepared)
* processing latency (time between input being sampled, usually at the start of an update cycle, and the results of that input being reflected in the world state used by the rendering)
* input latency (if your input devices don't immediately reflect the live state, it's possible your input sampling is actually based on the state some time ago. That's pretty rare nowadays, but depends on what input devices you're talking about)

Display and input latency are pretty much entirely out of your control, you typically can't choose what input device is being used or the settings/behaviour of the user's display device.

As to the others, the most obvious answer to minimising latency is **don't buffer frames**. You can choose to render less, and forego maximising your GPU/CPU parallelism, in favour of reduced latency. The next obvious answer is: render at 60Hz instead of 30Hz. That will cut your sync latency to 16ms. Again, to achieve that, you'll either have to render less, or render smarter. If you are running at just over 60Hz most of the time, but occasionally drop down, then rather than live with the massive hit of dropping to 30Hz, you can turn off lock-to-VSync, and live with those horrible screen tearing artifacts when you do take too long to render. However none of those options are great if you also want to make best use of your rendering power, which is why pretty much every modern game engine you see will buffer frames, and most of which run at 30Hz.

The next aspect relates to latency as a result of your simulation. Imagine a character jump. The user presses the jump button at time 0. If the visual feedback for jumping was just that the entire screen flashed yellow, then the latency would be purely based on your display chain (input -\> processing -\> rendering -\> presenting -\> displaying). With minimal processing, at 60Hz, on a CRT with minimal display lag, you could in theory see the yellow screen in about 30-40ms after your button press (less than one 16ms frame for input -\> processing -\> render, present on the first VSync at 16ms sharp, then the CRT displays some time after that).

Now imagine more typical visual feedback: the character animates - winds up and jumps. How many frames of animation does the character go through before they are obviously jumping? If it's more than 2 or 3, the simulation will feel 'laggy', not because the input isn't being processed immediately, but because the results of the input take some time to become obvious in the visual feedback.

This leads us to one of the better ways to make your game feel more responsive: run your simulation at 60Hz (or higher if you can). Even if you can't simulate **and** render at 60Hz, simulate (and sample input) at 60Hz anyway, and render based on the interpolated game state at any given point. You cannot avoid display latency, it will always be there, even if you try to minimise it. By decoupling your input / simulation loop from the rendering, you can sample input more frequently, and get more responsiveness in your physics, etc. As to why this is better? Read Mick's final paragraph in the original article on responsiveness: it's not so much about the player's reaction to what they see, as it is the games speed of reaction to what the player is doing. At a higher simulation speed, the game will react to the player more quickly. But there are other reasons to like a higher frequency simulation as well. Physics especially likes a smaller time-step, because there are fewer collisions and other discrete events per time-step that need resolved.

One of the nice things about that is if you do have a render-heavy system, you can actually drop the render rate to 20Hz and make use of that time, without the simulation part having problems because of the long slow time-steps. Of course, a 20Hz rendering will only make the display latency problem worse, I just throw it out there as a possibility once you've shifted to a decoupled simulation/render system.
> 10 votes

# Answer
The most obvious thing to do is to make sure that you process input before doing rendering, and that it actually has an effect in the next rendered frame. If you're not careful you can get things in the wrong order in the game loop and delay the result by a frame or more, especially when there's a long chain of processing between cause and effect (e.g. key press-\>physics system-\>animation system-\>renderer).

That is generally easy to test for and fix. Breakpoint the game at the beginning of the render loop, hold down an input then resume the game in the debugger so it runs one frame. If you can't see any effect then something is probably not right.

The other thing to watch out for is that when you're GPU bound, D3D will buffer three frames worth of rendering. This enables for example two graphics cards to work on separate frames simultaneously, however if you've only got one card it's just adding latency. You can use queries to limit this latency, but you need to use a variable number to avoid SLI issues - see page 6 of this Nvidia pdf.

There are also other sources of latency that you can't control like delays caused by the Monitor / TV. CRTs generally have a frame or two less lag than LCDs for example. You might find http://www.anandtech.com/show/2803/7 interesting.
> 2 votes

---
Tags: architecture, game-mechanics, input
---


# Question
Title: Is there a 2D soft-body physics engine for Flash?
I'd like to write a small physics game by using ActionScript, but do not want to write my own physics engine. Does anyone know a ready-to-use 2D soft-body physics engine with a Flash port?

# Answer
This one looks really good, based on Box2d.

http://code.google.com/p/quickb2/

I am currently dissecting the code for his top down car demo.
> 1 votes

---
Tags: flash, physics, actionscript-3
---


# Question
Title: GLSL Core Functionality Geometry Shader examples
I'm doing some research on geometry shaders and am having problems finding code examples/tutorials that does not use one of the extensions introduced before it was core functionality of OpenGL 3.2.

I'm looking for more modern approaches that doesn't use an extension.

Can anyone point me in the right direction?

I've already read the spec, but am looking for actually code examples.

# Answer
My tutorial on impostors has an example of using core geometry shaders. GS's aren't really the most useful things in the world, so it's hard to find legitimate examples. Indeed, the only future tutorial I have planned that uses them is for layered rendering for things like rendering to cube-maps.
> 4 votes

---
Tags: opengl, glsl
---