Java-Gaming.org Hi !
 Featured games (83) games approved by the League of Dukes Games in Showcase (580) Games in Android Showcase (162) games submitted by our members Games in WIP (632) games currently in development
 News: Read the Java Gaming Resources, or peek at the official Java tutorials
 Home Help Search Login Register
Pages: [1]
 ignore  |  Print
 Using Grids for collisions  (Read 4840 times) 0 Members and 1 Guest are viewing this topic.
SHC
 « Posted 2013-04-10 07:21:00 »

# Introduction

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.

 1  2  3 `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.

 1  2  3  4  5  6  7 `public class Entity {    public int x, y, width, height;    // Your entity methods}`

# Why using Grids

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.

# Our Goals with Grids

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

# Implementing the Grid

Now let's write a basic Grid class.

 1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40  41  42  43  44  45  46  47  48 `public class Grid {    // The actual grid array    private List[][] 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[cols][rows];    }    public void clear()    {        for (int x=0; x retrieve(Entity e)    {        // Retrieve the list of collide-able entities    }    public Entity getNearest(Entity e)    {        // Calculate and get the nearest entity    }}`

# Calculating the cells the Entity is in

To add an entity to the grid, we have to find the cells in which the entity fits.

 1  2 `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.

 1  2  3  4 `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.

 1  2  3  4 `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.

 1  2  3  4  5  6  7 `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.

# Retrieving the Entities

Since creating a list of entities each time causes increase in garbage, we create a private list called retrieveList to the class.

 1 `private List retrieveList = new ArrayList();`

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

 1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25 `public List 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 cell = grid[x][y];            // Add every entity in the cell to the list            for (int i=0; i

This method retrieves the entities which are likely to collide.

# Finding Nearest Entity

To find the nearest entity, we rely on the retrieve method.

 1 `List collidables = retrieve(entity);`

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

 1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21 `public Entity getNearest(Entity e){    // For comparisons    Entity nearest = null;    long distance = Long.MAX_VALUE;    // Retrieve the entities    List collidables = retrieve(e);    // Iterate and find the nearest    for (int i=0; i

# Conclusion

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).

Riven
« League of Dukes »

« JGO Overlord »

Medals: 959
Projects: 4
Exp: 16 years

Hand over your head.

 « Reply #1 - Posted 2013-04-10 10:32:03 »

 1  2  3  4 `-        rows = mapHeight / cellSize;-        cols = mapWidth / cellSize;+        rows = (mapHeight + cellSize - 1) / cellSize;+        cols = (mapWidth + cellSize - 1) / cellSize;`

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings!
Regenuluz
 « Reply #2 - Posted 2013-04-10 10:51:35 »

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)
 Games published by our own members! Check 'em out!
Riven
« League of Dukes »

« JGO Overlord »

Medals: 959
Projects: 4
Exp: 16 years

Hand over your head.

 « Reply #3 - Posted 2013-04-10 11:26:54 »

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

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings!
SHC
 « Reply #4 - Posted 2013-04-10 11:46:57 »

@Riven,

I'm using

 1  2 `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?

Riven
« League of Dukes »

« JGO Overlord »

Medals: 959
Projects: 4
Exp: 16 years

Hand over your head.

 « Reply #5 - Posted 2013-04-10 11:51:50 »

Quote
I'm using

 1  2 `rows = mapHeight / cellSize;cols = mapWidth / cellSize;`

because mapWidth and mapHeight are in pixels.

An example then: say your mapWidth=100 and your cellSize=26, then cols=3, while it should be 4.

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings!
relminator
 « Reply #6 - Posted 2013-04-10 12:01:35 »

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:

Quote
And BSPTrees are for 3D space. Though QuadTrees are usefull for some extent, they are less faster than Grids. So let's implement a Grid.

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. '*)

Regenuluz
 « Reply #7 - Posted 2013-04-10 12:13:08 »

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.'
SHC
 « Reply #8 - Posted 2013-04-10 12:21:06 »

@Riven,

Thanks for pointing that out. Changed it.

@Relminator,

You're right, changed that sentence.

SHC
 « Reply #9 - Posted 2013-04-10 12:28:54 »

@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.

Pages: [1]
 ignore  |  Print

You cannot reply to this message, because it is very, very old.

 Waterwolf (20 views) 2015-05-20 15:01:45 chrislo27 (25 views) 2015-05-20 03:42:21 BurntPizza (59 views) 2015-05-10 15:53:18 FrozenShade (45 views) 2015-05-07 09:11:21 TheLopais (208 views) 2015-05-06 13:36:48 TheLopais (191 views) 2015-05-06 13:35:14 TheLopais (198 views) 2015-05-06 13:33:39 TheLopais (214 views) 2015-05-06 13:32:48 TheLopais (214 views) 2015-05-06 13:31:28 ClaasJG (236 views) 2015-04-30 20:33:25
 Spasi 31x BurntPizza 16x theagentd 13x DavidBVal 13x ra4king 12x EgonOlsen 11x Husk 10x KevinWorkman 9x princec 8x scanevaro 8x KaiHH 7x opiop65 6x revers 6x Riven 6x HeroesGraveDev 5x MrPork 5x
 List of Learning Resources2015-05-05 10:20:32How to: JGO Wikiby Mac702015-02-17 20:56:162D Dynamic Lighting2015-01-01 20:25:42How do I start Java Game Development?by gouessej2014-12-27 19:41:21Resources for WIP gamesby kpars2014-12-18 10:26:14Understanding relations between setOrigin, setScale and setPosition in libGdx2014-10-09 22:35:00Definite guide to supporting multiple device resolutions on Android (2014)2014-10-02 22:36:02List of Learning Resources2014-08-16 10:40:00
 java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org