3

I'm working on a "game" in my spare time, almost purely as a learning experience, and am at the point where collision detection between the player entity and enemy entities needs to occur.

Both the player and all enemies share a base class, Entity, which gives them access to x, y, height, and width properties. Using these, I can build a rectangle for each entity, and try to find overlaps. If there is an overlap, a collision has occurred.

So, with the logic above, we can pretend that the following data is in an array of Rectangles:

X    Y    HEIGHT   WIDTH
------------------------
0    0    25       50
0    50   25       25
0    100  25       30
50   200  25       50
150  250  25       25
150  50   25       30

What is the fastest way to determine if any of those entities (Rectangles) are intersecting with any other? Simply looping through the array and comparing each element to each other element is not performant enough (O(n^2)). Is there a better way?

Mike Trpcic
  • 25,305
  • 8
  • 78
  • 114
  • I would create a course-grained "background grid". The object "registers" itself in the course-grained grid-cells for which it overlaps. You can then do an O(n^2) on each course grained grid cell. (In general it shouldn't be more than a couple of objects in each cell, so it will be "close" to O(n) in practice) – aioobe Nov 16 '12 at 19:57
  • 1
    Not performant enough? How many rectangles do you have? – Sergey Kalinichenko Nov 16 '12 at 19:57
  • 2
    Do you need to know which one is intersecting or only the fact that something is intersceting is enough to you? – Daniel Pereira Nov 16 '12 at 19:58

1 Answers1

6

You want to use some sort of spatial index or structure that allows you to quickly find elements that are near each other.

One commonly used data structure is a quadtree.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • Could you elaborate on how to find nearby objects if they are structured in a quadtree according to their x/y coordinates? (I'm having problems to see what should happen close to the center, where the root is the closest common ancestor to the neighboring "leaf-cells".) – aioobe Nov 16 '12 at 21:01