Game Development Reference
In-Depth Information
This is called a spatial hash grid broad phase, and it is very easy to implement. The first thing
you have to define is the size of each cell. This is highly dependent on the scale and units you
use for your game's world.
An Elaborate Example
We'll develop a spatial hash grid broad phase based on the previous cannonball example
(located in the “Playing Around, Practically� section). We will completely rework it to incorporate
everything covered in this section so far. In addition to the cannon and the cannonball, we also
want to have targets. We make our life easy and just use 0.5Ă—0.5-m squares as targets. These
squares don't move; they're static. Our cannon is also static. The only thing that moves is the
cannonball itself. We can generally categorize objects in our game world as static objects or
dynamic objects. Let's devise a class that represents such objects.
GameObject, DynamicGameObject, and Cannon
Let's start with the static case, or base case, in Listing 8-7.
Listing 8-7. GameObject.java, a Static Game Object with a Position and Bounds
package com.badlogic.androidgames.framework;
import com.badlogic.androidgames.framework.math.Rectangle;
import com.badlogic.androidgames.framework.math.Vector2;
public class GameObject {
public final Vector2 position;
public final Rectangle bounds;
public GameObject( float x, float y, float width, float height) {
this .position = new Vector2(x,y);
this .bounds = new Rectangle(x-width/2, y-height/2, width, height);
}
}
Every object in our game has a position that coincides with its center. Additionally, we let each
object have a single bounding shape—a rectangle, in this case. In the constructor, we set the
position and bounding rectangle (which is centered around the center of the object) according
to the parameters.
For dynamic objects (that is, objects which move), we also need to keep track of velocity and
acceleration (if they objects are actually accelerated by themselves—for example, via an engine
or thruster). Listing 8-8 shows the code for the DynamicGameObject class.
 
Search WWH ::




Custom Search