Search code examples
vb.netcollision-detectioncollision

When to check for collision


I have a moving mars lander which I want to detect when it hits the top of a refuelling station in a game I'm making. I want to know the best way to know exactly when they hit.

What I am doing at the moment is I have 3 timers controlling horizontal, vertical and gravitational movement. Each timer makes the mars lander move a bit so I put the crash detection code at the top and bottom of each of these but since each one is fireing every 50 milliseconds a) it wont detect exactly when it collides and b) it will call the crash detection code a lot of times.

This is what one of the timers looks like and its pretty much the same for all 3 (I am making the game in vb 2008, this is just some pseudo-code):

gravity timer:
    detectCrash()
    Move ship 
    detectCrash()
End timer
  1. what would be a more accurate way to see if they are colliding in terms of response time from the collide to the code which that calls.

  2. how would I call the detection a lower amount of times?

I could possibly make another timer that fires every 10 milliseconds or so and check the collision but then this will run the code an awful lot of times (100 times a second) wont it?

I am also curious as to how large games would handle something like this which most likely happens many times a second.

Thanks.


Solution

  • You don't want to have separate timers for moving the object and for detecting collisions. This approach has a couple of obvious problems:

    • It doesn't scale at all; imagine adding more objects. Would you have two timers for each (one each for the X and Y planes)? Would you add yet another timer to detect collisions for each object?
    • It's possible for the timers to get out of sync - imagine your code for moving your ship in the X plane takes much longer to run than the code for the Y plane. Suddenly your ship is moving vertically more often than it's moving horizontally.

    'Real' games have a single loop, which eliminates most of your problems. In pseudo-code:

    1. Check for user input
    2. Work out new X and Y position of ship
    3. Check for collisions
    4. Draw result on screen
    5. Goto 1

    Obviously, there's more to it than that for anything more than a simple game! But this is the approach you want, rather than trying to have separate loops for everything you've got going on.