Game Development Reference
In-Depth Information
int len = dynamicCells[cellId].size();
for ( int j = 0; j < len; j++) {
GameObject collider = dynamicCells[cellId].get(j);
if if(!foundObjects.contains(collider))
foundObjects.add(collider);
}
len = staticCells[cellId].size();
for ( int j = 0; j < len; j++) {
GameObject collider = staticCells[cellId].get(j);
if if(!foundObjects.contains(collider))
foundObjects.add(collider);
}
}
return foundObjects;
}
Finally, the getPotentialColliders() method takes an object and returns a list of neighboring
objects that are contained in the same cells as that object. We use the working list foundObjects
to store the list of found objects. Again, e do not want to instantiate a new list each time
this method is called. All we need to do is figure out which cells the object passed to the
method is in. We then simply add all the dynamic and static objects found in those cells to the
foundObjects list and make sure that there are no duplicates. Using foundObjects.contains()
to check for duplicates is, of course, suboptimal, but given that the number of found objects will
never be large, it is acceptable to use it in this case. If we run into performance problems, then
this is our number one candidate for optimization. Sadly, this isn't trivial. We can use a Set , of
course, but that allocates new objects internally each time we add an object to it. For now,
we just leave it as it is, knowing that we can come back to it if anything goes wrong
performance-wise.
The method left out is SpatialHashGrid.getCellIds() . Listing 8-11 shows its code. Don't be
afraid, it just looks menacing.
Listing 8-11. The Rest of SpatialHashGrid.java; Implementing getCellIds()
public int [] getCellIds(GameObject obj) {
int x1 = ( int )FloatMath. floor (obj.bounds.lowerLeft.x / cellSize);
int y1 = ( int )FloatMath. floor (obj.bounds.lowerLeft.y / cellSize);
int x2 = ( int )FloatMath. floor ((obj.bounds.lowerLeft.x + obj.bounds.width) / cellSize);
int y2 = ( int )FloatMath. floor ((obj.bounds.lowerLeft.y + obj.bounds.height) / cellSize);
if (x1 == x2 && y1 == y2) {
if (x1 >= 0 && x1 < cellsPerRow && y1 >= 0 && y1 < cellsPerCol)
cellIds[0] = x1 + y1 * cellsPerRow;
else
cellIds[0] = -1;
cellIds[1] = -1;
cellIds[2] = -1;
cellIds[3] = -1;
}
else if (x1 == x2) {
int i = 0;
 
Search WWH ::




Custom Search