8

For example, your game has 100 enemies (on different teams) running around and their AI wants to inspect the nearby entities to see which it should attack. What is a fast way to organize those entities so that each enemy does not have to calculate the distance between itself and all other entities?

In short, what is a fast way for an AI entity to answer the question "Who is near me?"

khayman218
  • 135
  • 1
  • 5

2 Answers2

8

You want a spatial index such as quadtree (2D) or octree (3D).

Will
  • 6,977
  • 4
  • 36
  • 59
  • 1
    @FxIII I'm not sure I follow at all what you are on about. These spatial tree datastructures are specifically designed to answer the poster's question, and are well understood and used. – Will Aug 19 '11 at 06:27
5

The simplest solution is a grid. Lay a 2D grid over your level. Each cell in the grid maintains a collection of which entities are currently occupying it. As the entities move, take them out of the cell they're leaving and add them to the one they enter.

You can then find nearby entities just by examining the nearby cells. A quadtree refines this by recursively subdividing the grid, but sometimes a flat one is adequate, especially if your level size is fixed and relatively small.

munificent
  • 12,045
  • 4
  • 34
  • 35