Thursday, May 10, 2007

When to Check Collision Detection?

This post is not going to cover the actual detection of collisions between sprites; I think there's already more than enough of that on the net for a lifetimes reading. I'm talking about "when" we check for collisions...

I previously used to process all my game objects sequentially, and check for collisions against every other object. However, the problem with this is that the program will be checking for collisions between object A and object B, and then checking object B for collisions with object A. This is time wasted, as presumably if object A hasn't hit object B, then object B hasn't hit object A. (This assumes that all object movement has been carried out already)

What I now do is loop through each object, and only check for collisions against all the objects placed after the current object in the game's "list of objects". So object A is checked against object B and C, and object B now checks only against object C, whereas previously it would also have checked against object A as well.

So if my game had 100 objects, it was checking for collisions 9,900 times in each game loop (100 objects x 99 other objects). However it now only checks 4,950 (I think) times!

No comments: