Tuesday, July 08, 2008

Collision detection code is usually one of the most CPU intensive part of any game engine. Done improperly, it can severely cripple your frame rate, and worse, make your game looks unrealistic. After all, it's never realistic to see a bullet flying through thick walls or one car stacking on top of another.

One important key to doing collision detection is to know when not to do it. If you could reject a potential test early on, then you just saved yourself some CPU there. Another thing to be mindful of is the boundary condition. That is, what happen if a bullet is on one side of the wall in this render cycle, but appears on the next side of the wall in the next render cycle? What happen if your game is running on a slow machine and therefore render at a very low frame rate? Usually that means your collision detection code will get call less, making it less accurate and therefore all that more important to work for things that are moving at relatively higher speed.

Let's say you have a driving game that is a top-down scroller. In the game, the player's car can switch lane very quickly. To reduce the amount of collision detection needed, you have made it so that the player's car only detects for collision when it's switching lane. Let's also assume that you employ a very simple scheme of collision detection by using hitTest of the player's car against all the cars in the next lane that is' switching to. In the event of collision, the car will abort its lane changing operation and goes back to its original lane. If the car has successfully switches lane without hitting any car in the process (based on when its position snaps with the new lane's position), no lane change abortion will be performed.

Now imagine everything is going good, and suddenly your game is running at 10fps. That means your collision code will only be run every 100msec. One very possible scenario is that the collision code only gets to run once while the car is switching lane, and the next time it runs, the car has already snapped onto the new lane and then collide with another car there. But since the lane change has already finished, it will not abort and end up getting stuck on top of that car.

In a situation like this, a simple hitTest might not suffice. You will likely need to employ a different collision check scheme (such as a simple ray trace), enlarge the bounding box of the car when the frame rate is low, etc.

As you can see, collision detection is a huge subject, knowing and doing it properly is the key to making your game perform well both from the performance standpoint and gameplay standpoint.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home