Game Development Reference
In-Depth Information
The final portion of this method is our collision detection code. We find the targets in the
spatial hash grid that are in the same cells as our cannonball. We use the SpatialHashGrid.
getPotentialColliders() method for this. Since the cells in which the ball is contained are
evaluated in that method directly, we do not need to insert the ball into the grid. Next, we loop
through all the potential colliders and check to see if there really is an overlap between the ball's
bounding rectangle and a potential collider's bounding rectangle. If there is, we simply remove
the target from the target list. Remember, we only add targets as static objects to the grid.
And those are our complete game mechanics. The last piece of the puzzle is the actual
rendering, which shouldn't really surprise you. See the code in Listing 8-14.
Listing 8-14. Excerpt from CollisionTest.java; the present() Method
@Override
public void present( float deltaTime) {
GL10 gl = glGraphics.getGL();
gl.glViewport(0, 0, glGraphics.getWidth(), glGraphics.getHeight());
gl.glClear(GL10. GL_COLOR_BUFFER_BIT );
gl.glMatrixMode(GL10. GL_PROJECTION );
gl.glLoadIdentity();
gl.glOrthof(0, WORLD_WIDTH, 0, WORLD_HEIGHT, 1, -1);
gl.glMatrixMode(GL10. GL_MODELVIEW );
gl.glColor4f(0, 1, 0, 1);
targetVertices.bind();
int len = targets.size();
for ( int i = 0; i < len; i++) {
GameObject target = targets.get(i);
gl.glLoadIdentity();
gl.glTranslatef(target.position.x, target.position.y, 0);
targetVertices.draw(GL10. GL_TRIANGLES , 0, 6);
}
targetVertices.unbind();
gl.glLoadIdentity();
gl.glTranslatef(ball.position.x, ball.position.y, 0);
gl.glColor4f(1,0,0,1);
ballVertices.bind();
ballVertices.draw(GL10. GL_TRIANGLES , 0, 6);
ballVertices.unbind();
gl.glLoadIdentity();
gl.glTranslatef(cannon.position.x, cannon.position.y, 0);
gl.glRotatef(cannon.angle, 0, 0, 1);
gl.glColor4f(1,1,1,1);
cannonVertices.bind();
cannonVertices.draw(GL10. GL_TRIANGLES , 0, 3);
cannonVertices.unbind();
}
Nothing new here. As always, we set the projection matrix and viewport, and clear the screen
first. Next, we render all targets, reusing the rectangular model stored in targetVertices . This is
Search WWH ::




Custom Search