Game Development Reference
In-Depth Information
All this method does is make a special case for each of these possibilities. The first if statement
checks for the single-cell case, the second if statement checks for the horizontal double-cell
case, the third if statement checks for the vertical double-cell case, and the else block handles
the case of an object overlapping four grid cells. In each of the four blocks, we make sure that
we only set the cell ID if the corresponding cell coordinates are within the world. And that's all
there is to this method.
Now, the method looks like it should take a lot of computational power. And indeed it does, but
less than its size would suggest. The most common case will be the first one, and processing
that is pretty cheap. Can you see opportunities to optimize this method further?
Putting It All Together
Let's put together all the knowledge we gathered in this section to form a nice little example.
We can extend the cannon example of the last section, as discussed a few pages back. We
use a Cannon object for the cannon, a DynamicGameObject for the cannonball, and a number of
GameObject s for the targets. Each target will have a size of 0.5×0.5 m and be placed randomly in
the world.
We want to be able to shoot these targets. For this, we need collision detection. We could just
loop over all targets and check them against the cannonball, but that would be boring. We use
our fancy new SpatialHashGrid class to speed up the process of finding potential-collision
targets for the current ball position. We don't insert the ball or the cannon into the grid, though,
as that wouldn't really help you.
Since this example is already pretty big, it's split it into multiple listings. Call the test
CollisionTest and the corresponding screen CollisionScreen . As always, we only look at the
screen code. Let's start with the members and the constructor in Listing 8-12.
Listing 8-12. Excerpt from CollisionTest.java; Members and Constructor
class CollisionScreen extends Screen {
final int NUM_TARGETS = 20;
final float WORLD_WIDTH = 9.6f;
final float WORLD_HEIGHT = 4.8f;
GLGraphics glGraphics;
Cannon cannon;
DynamicGameObject ball;
List<GameObject> targets;
SpatialHashGrid grid;
Vertices cannonVertices;
Vertices ballVertices;
Vertices targetVertices;
Vector2 touchPos = new Vector2();
Vector2 gravity = new Vector2(0,-10);
public CollisionScreen(Game game) {
super (game);
glGraphics = ((GLGame)game).getGLGraphics();
 
Search WWH ::




Custom Search