Grid collision - finding the location of an entity in each box
Posted
by
Gregg1989
on Game Development
See other posts from Game Development
or by Gregg1989
Published on 2014-02-09T15:52:56Z
Indexed on
2014/06/09
21:42 UTC
Read the original article
Hit count: 196
I am trying to implement grid-based collision in a 2d game with moving circles. The canvas is 400x400 pixels. Below you can see the code for my Grid class. What I want it to do is check inside which box the entities are located and then run a collision check if there are 2 or more entities in the same box.
Right now I do not know how to find the position of an entity in a specific box. I know there are many tutorials online, but I haven't been able to find an answer to my question, because they are either written in C/C++ or use the 2d array approach.
Code snippets and other help is greatly appreciated. Thanks.
public class Grid {
ArrayList<ArrayList<Entity>> boxes = new ArrayList<>();
double boxSize = 40;
double boxesAmount = 10;
...
...
public void checkBoxLocation(ArrayList<Entity> entities) {
for (int i = 0; i < entities.size(); i++) {
// Get top left coordinates of each entity
double entityLeft = entities.get(i).getLayoutX() - entities.get(i).getRadius();
double entityTop = entities.get(i).getLayoutY() + entities.get(i).getRadius();
// Divide coordinate by box size to find the approximate location of the entity
for (int j = 0; j < boxesAmount; j++) { //Select each box
if ((entityLeft / boxSize <= j + 0.7) && (entityLeft / boxSize >= j)) {
if ((entityTop / boxSize <= j + 0.7) && (entityTop / boxSize >= j)) {
holdingBoxes.get(j).add(entities.get(i));
System.out.println("Entity " + entities.get(i) + " added to box " + j);
}
}
}
}
}
}
© Game Development or respective owner