Using Grids for collisions

[h1]Introduction[/h1]
In this tutorial, we’re going to construct a Grid to check for collisions in a 2D map. Here are some of the variables we’ll be using.


int mapWidth;        // Width of map (in pixels)
int mapHeight;       // Height of map (in pixels)
int cellSize;        // The size of each cell in the grid

And here’s the basic Entity class we’ll be using.


public class Entity {

    public int x, y, width, height;

    // Your entity methods

}

[h1]Why using Grids[/h1]
If the entities in the map are less than 50, the brute force collision method is fine. But it is dead slow if the number of entities tend to increase. So if the map has 100 entities, we need 4950 checks for collision detection. So here comes the idea of binary partitioning. There are many forms of it. Some of them are QuadTrees, Octrees (or) kdTrees, BSPTrees, bins (or) Grids.

For 2D maps, QuadTrees and Grids are the most popular. And BSPTrees are for 3D space.
Quadtrees should be faster than grids on scenes with lots of entities. However, if the target platforms have slow rams, grids are way to go since you get penalty for accessing non-contigous data in memory. So let’s implement a Grid.

[h1]Our Goals with Grids[/h1]
We can use grids to

  • Differentiate the entities in to Cells
  • Retrieve a list of entities which are likely to collide with a given entity and
  • Find nearest entity of another entity

[h1]Implementing the Grid[/h1]
Now let’s write a basic Grid class.


public class Grid {

    // The actual grid array
    private List<Entity>[][] grid = null;

    // The rows and columns in the grid
    private int rows, cols;

    // The cell size
    private int cellSize;

    public Grid ( int mapWidth, int mapHeight, int cellSize)
    {
        this.cellSize = cellSize;
        // Calculate rows and cols
        rows = (mapHeight + cellSize - 1) / cellSize;
        cols = (mapWidth + cellSize - 1) / cellSize;
        // Create the grid
        grid = new ArrayList<Entity>[cols][rows];
    }

    public void clear()
    {
        for (int x=0; x<cols; x++)
        {
            for (int y=0; y<rows; y++)
            {
                grid[x][y].clear();
            }
        }
    }

    public void addEntity(Entity e)
    {
        // Add the entity to the grid
    }

    public List<Entity> retrieve(Entity e)
    {
        // Retrieve the list of collide-able entities
    }

    public Entity getNearest(Entity e)
    {
        // Calculate and get the nearest entity
    }

}

[h1]Calculating the cells the Entity is in[/h1]
To add an entity to the grid, we have to find the cells in which the entity fits.


int cellX = entity.x / cellSize;
int cellY = entity.y / cellSize;

The problem with this code is that it only finds the cell which is the top left in the cells the entity is in. But we need all the cells the object is in. So we calculate the top left and bottom right points and add all the cells in between.


int topLeftX = entity.x / cellSize;
int topLeftY = entity.y / cellSize;
int bottomRightX = (entity.x + entity.width - 1) / cellSize;
int bottomRightY = (entity.y + entity.height - 1) / cellSize;

We also need to check that the coordinates are in the grid only. We’ve to limit the negative cells and cells outside the map’s bounds.


int topLeftX = Math.max(0, entity.x / cellSize);
int topLeftY = Math.max(0, entity.y / cellSize);
int bottomRightX = Math.min(cols-1, (entity.x + entity.width -1) / cellSize);
int bottomRightY = Math.min(rows-1, (entity.y + entity.height -1) / cellSize);

And now let’s loop through them and add to all the cells.


for (int x = topLeftX; x <= bottomRightX; x++)
{
    for (int y = topLeftY; y <= bottomRightY; y++)
    {
        grid[x][y].add(entity);
    }
}

This adds the entity to all the cells overlapping it.

[h1]Retrieving the Entities[/h1]
Since creating a list of entities each time causes increase in garbage, we create a private list called retrieveList to the class.


private List<Entity> retrieveList = new ArrayList<Entity>();

We reuse this object every time we search for objects. Here’s how we retrieve the objects.


public List<Entity> retrieve(Entity e)
{
    retrieveList.clear();
    // Calculate the positions again
    int topLeftX = Math.max(0, e.x / cellSize);
    int topLeftY = Math.max(0, e.y / cellSize);
    int bottomRightX = Math.min(cols-1, (e.x + e.width -1) / cellSize);
    int bottomRightY = Math.min(rows-1, (e.y + e.height -1) / cellSize);
    for (int x = topLeftX; x <= bottomRightX; x++)
    {
        for (int y = topLeftY; y <= bottomRightY; y++)
        {
            List<Entity> cell = grid[x][y];
            // Add every entity in the cell to the list
            for (int i=0; i<cell.size(); i++)
            {
                Entity retrieved = cell.get(i);
                // Avoid duplicate entries
                if (!retrieveList.contains(retrieved))
                    retrieveList.add(retrieved);
            }
        }
    }
    return retrieveList;
}

This method retrieves the entities which are likely to collide.

[h1]Finding Nearest Entity[/h1]
To find the nearest entity, we rely on the retrieve method.


List<Entity> collidables = retrieve(entity);

Then iterate over it and select the entity for which the distance is less. Here’s the complete method.


public Entity getNearest(Entity e)
{
    // For comparisons
    Entity nearest = null;
    long distance = Long.MAX_VALUE;
    // Retrieve the entities
    List<Entity> collidables = retrieve(e);
    // Iterate and find the nearest
    for (int i=0; i<collidables.size(); i++)
    {
        Entity toCheck = collidables.get(i);
        // Check the distance
        long dist = (toCheck.x-e.x)*(toCheck.x-e.x) + (toCheck.y-e.y)*(toCheck.y-e.y);
        if (dist < distance)
        {
            nearest = toCheck;
            distance = dist;
        }
    }
    return nearest;
}

[h1]Conclusion[/h1]
Thanks for reading this article. It would be useful in most games. Please post any errors that might be crept in (I’m not good at writing articles).


-        rows = mapHeight / cellSize;
-        cols = mapWidth / cellSize;
+        rows = (mapHeight + cellSize - 1) / cellSize;
+        cols = (mapWidth + cellSize - 1) / cellSize;

Shouldn’t it be noted that it’s faster to repopulate the grid every tick, than to remove an object from the cells and then add it to another? (At least that’s what I’ve gathered from reading this forum)

Whether it is faster to repopulate grid cells or move individual entities from cell to cell, depends on entity count and their speed.

@Riven,

I’m using


rows = mapHeight / cellSize;
cols = mapWidth / cellSize;

because mapWidth and mapHeight are in pixels.

And how did you highlight lines in code tag?

@Regenuluz

“Clearing is faster than remove method”. I heard this more on this forum. Won’t creating new instances every loop create garbage?

[quote]I’m using


rows = mapHeight / cellSize;
cols = mapWidth / cellSize;

because mapWidth and mapHeight are in pixels.
[/quote]
An example then: say your mapWidth=100 and your cellSize=26, then cols=3, while it should be 4.

Cool article!

I’ve used grids before doing some 13h particle physics based on Hugo Elias’ grid article (forgot the linky).

While grids are “sometimes” faster than a tree-based space partitioning system, these sentences needs a little edit:

You might want to change “BSPTrees” to octrees and kdtrees since BSP trees does not work like a grid.

Quadtrees should be faster than grids on scenes with lots of entities. However, if your target platforms have slow rams, grids are way to go since you get penalty for accessing non-contigious data in memory. Then again you are using lists for your grid. '*)

SHC, I suppose creating new objects every tick would create a lot of garbage. Only way, that I can see, around that, would be to store all entities in a list and then iterate through that list and add them to the grid. (Not sure how much extra ram this’d use extra though, probably not twice as much because of pointers.) Thus when you remove an entity from the list of entities, it’ll be removed from the grid ‘automatically.’

@Riven,

Thanks for pointing that out. Changed it.

@Relminator,

You’re right, changed that sentence.

@Regenuluz

That’s what I always use. I store them in a list in the map class and add them after the update and check collisions. Also I forgot to add a clear method in the class to clear the lists.