Search code examples
javascripthtmlcanvascollision-detection

Directional collision detection


If I want to move an object 40 pixels every second and I have the following scenario, how can I efficiently detect that there was a collision?

Assume both objects are 10 by 10 squares

Starting point of moving object at 2 seconds:

40, 100

Ending point of moving object at 3 seconds:

80, 100

Stagnant object at 60, 100

If I am only moving the moving object once (from 40 to 80 without any movements in between) how would I tell there was an object between them?

This is obviously a simplified version of what I am doing but I wanted it to be easy to understand.

The only thing I can think of is check if each object has a side with an x value less than 80 and another side with an x value greater than 40 and the same idea with y values...

I'll be using javascript and html5 canvas if that makes any difference.


Solution

  • You could try to determine if there was a collision with the bounding rectangle defined by the start and end positions of the moved object:

    +-----------+--+
    |     +==+  |  |
    +-----:  :--+--+
          +==+