Game Development Reference
In-Depth Information
world, looking down the negative z axis. We therefore rotate and translate the objects around the
camera, not the other way around.
final float [] matrix = new float [16];
final float [] inVec = { 0, 0, -1, 1 };
final float [] outVec = new float [4];
final Vector3 direction = new Vector3();
public Vector3 getDirection() {
Matrix. setIdentityM (matrix, 0);
Matrix. rotateM (matrix, 0, yaw, 0, 1, 0);
Matrix. rotateM (matrix, 0, pitch, 1, 0, 0);
Matrix. multiplyMV (outVec, 0, matrix, 0, inVec, 0);
direction.set(outVec[0], outVec[1], outVec[2]);
return direction;
}
}
Finally, we have the mysterious getDirection() method. It is accompanied by a couple of
final members that we use for the calculations inside the method. We do this so that we don't
allocate new float arrays and Vector3 instances each time the method is called. Consider those
members to be temporary working variables.
Inside the method, we first set up a transformation matrix that contains the rotation around the
x and y axes. We don't need to include the translation, since we only want a direction vector,
not a position vector. The direction of the camera is independent of its location in the world.
The Matrix methods we invoke should be self-explanatory. The only strange thing is that we
actually apply them in reverse order, without negating the arguments. We do the opposite in the
setMatrices() method. That's because we are now actually transforming a point in the same
way that we'd transform our virtual camera, which does not have to be located at the origin or
be oriented so that it looks down the negative z axis. The vector we rotate is (0,0,-1), stored
in inVec . That's the default direction of our camera if no rotation is applied. All that the matrix
multiplications do is rotate this direction vector by the camera's pitch and roll so that it points in
the direction that the camera is heading. The last thing we do is set a Vector3 instance based on
the result of the matrix-vector multiplication, and return that to the caller. We can use this unit-
length direction vector later on to move the camera in the direction it is heading.
Equipped with this little helper class, we can write a tiny example program that allows us to
move through a world of crates.
An Euler Camera Example
We now want to use the EulerCamera class in a little program. We want to be able to rotate the
camera up and down and left and right, based on swiping the touchscreen with a finger. We
also want it to move forward when a button is pressed. Our world should be populated by a few
dozen of crates. Figure 11-10 shows the initial setup of our scene.
 
Search WWH ::




Custom Search