Search code examples
algorithmcollision-detection2d-games

Fast algorithm for detecting if a rectangular shape intersects a rectangular boundary


Imagine you have a yard with fence around it, which might look like this:

 ______  ________
|      |_|      _|
|              |_
|        _    ___|
|__     |_|  |  
   |         |__
___|      _     |
|        | |    |_
|________| |______|

Don't ask why it's a weird shape, it's your yard, I didn't make it. 

..where that little box in the middle is some arbitrary squarish object. If that object where to move in any direction toward the edge of your yard, how would you detect when the object collided with your fence?

What if your yard were thousands of times bigger and there were many edges to keep track of? How would you efficiently solve this problem then?


Solution

  • View the yard as a large rectangle with several "negative" squares removed from it.

    Store the locations of these negative squares in a quad tree.

    To check for collision, probe the tree for the four squares adjacent to the object.

    The time complexity of the detection operation depends on the choice of quad tree variant, but you can expect logarithmic time in the number of negative squares.