Game Development Reference
In-Depth Information
How to do it...
We can implement almost everything we need in a single class as follows:
1. We begin by creating a class called
EdgeCheckControl
, which extends
Ab-
stractControl
and contains the following fields, as shown in the following
code:
private Ray[] rays = new Ray[9];
private float okDistance = 0.3f;
private Spatial world;
private boolean nearEdge;
2. We define the nine rays that will be used for collision detection. In the
setSpa-
tial
method, we instantiate them and aim them downwards, as shown in the fol-
lowing code:
for(int i = 0; i < 9; i++){
rays[i] = new Ray();
rays[i].setDirection(Vector3f.UNIT_Y.negate());
}
3. In the
controlUpdate
method, we begin by placing one of the rays at the cen-
ter of the character, as shown in the following code:
Vector3f origo = getSpatial().getWorldTranslation();
rays[0].setOrigin(origo);
4. We step around the character, placing the remaining rays in a circular shape. For
each, we see whether it collides with something using the
checkCollision
method. If it doesn't, we don't need to check the rest and can exit the loop using the
following code:
float angle;
for(int i = 1; i < 9; i++){
float x = FastMath.cos(angle);
float z = FastMath.sin(angle);
rays[i].setOrigin(origo.add(x * 0.5f, 0, z * 0.5f));
collision = checkCollision(rays[i]);