Java-Gaming.org Hi !
Featured games (83)
games approved by the League of Dukes
Games in Showcase (538)
Games in Android Showcase (132)
games submitted by our members
Games in WIP (600)
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 3965 times)
0 Members and 1 Guest are viewing this topic.
Offline 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<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
    }

}

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<Entity> retrieveList = new ArrayList<Entity>();

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

Finding Nearest Entity


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

1  
List<Entity> 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<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;
}

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

Offline Riven
« League of Dukes »

« JGO Overlord »


Medals: 840
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
Offline 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!
Legends of Yore - The Casual Retro Roguelike
Offline Riven
« League of Dukes »

« JGO Overlord »


Medals: 840
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
Offline 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?

Offline Riven
« League of Dukes »

« JGO Overlord »


Medals: 840
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
Offline 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. '*)

Offline 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.'
Offline 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.

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

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

rwatson462 (29 views)
2014-12-15 09:26:44

Mr.CodeIt (20 views)
2014-12-14 19:50:38

BurntPizza (40 views)
2014-12-09 22:41:13

BurntPizza (76 views)
2014-12-08 04:46:31

JscottyBieshaar (37 views)
2014-12-05 12:39:02

SHC (50 views)
2014-12-03 16:27:13

CopyableCougar4 (47 views)
2014-11-29 21:32:03

toopeicgaming1999 (114 views)
2014-11-26 15:22:04

toopeicgaming1999 (102 views)
2014-11-26 15:20:36

toopeicgaming1999 (30 views)
2014-11-26 15:20:08
Resources for WIP games
by kpars
2014-12-18 10:26:14

Understanding relations between setOrigin, setScale and setPosition in libGdx
by mbabuskov
2014-10-09 22:35:00

Definite guide to supporting multiple device resolutions on Android (2014)
by mbabuskov
2014-10-02 22:36:02

List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50
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
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!