Search code examples
c#xnacollision-detectionxna-4.0

XNA collission detection vs. game speed


I have been coding for some years in C# and have now decided to try out the XNA framework to make games.

It went great until I started to implement collision handling in my very simple game.

I can understand how to do collision detection using BoundingBoxes and BoundingSpheres, but after looking at the refresh rate in my game, it quickly became a concern of mine if the two colliding objects were never detected as colliding.

Let me try to explain with an example: - If a character is shooting with a gun at another character. - The bullet is heading straight for the other character. - The bullet gets rendered just before the character. - Because of the bullets high velocity it now gets rendered on the other side of the character.

In this scenario the bullet and the character never collides, because they are never rendered in their colliding state.

So how do you make sure to detect a collision in this scenario?


Solution

  • For very fast-moving objects, the regular approach fails in the scenario you described. What you need to check for is whether the bullet has collided with any item in the interval between the two consecutive game ticks. This is called continuous collision detection (this is a rather related SO post).

    You can do this by basically casting a ray between the middle of the bullet's binding box in the current position and the middle of the box from the old position, and checking if that collides with any other blocks/spheres. This is a rather fast solution and if your bullets are small enough, it should work fine.

    For more precision, you can cast four different so-called collision rays from each corner of the current bullet box, to their corresponding positions from the previous game tick. Note that in the rare event of high-speed items smaller than bullets, this might also fail. In this case you would need a more advanced collision detection system. But this would just be a corner case.

    If that extra precision is a must, a free 3D physics library, such as Bullet could represent a solution. It even has bindings for XNA!