Game Development Reference
In-Depth Information
How to do it...
To make the camera follow units, perform the following steps:
1. We start by adding two new variables, which we'll use for the new functionality. A
Vector3f variable, called targetLocation , will be used to track the target, and
a Boolean variable called follow , will be used to declare whether the camera
should track the target or not. These are set from external classes.
2. Out of convenience, we also define a final Vector3f variable, called UNIT_XZ ,
which we set to (1f, 0, 1f) . We'll use this to convert 3D positions to 2D.
3. Then, we need to add some functionality in the update method just before
cam.setLocation(camLocation); .
4. First, we add a check to see whether the camera has been moved by the player. If
so, we turn off the tracking as follows:
if(tempVector.length() > 0){
follow = false;
}
5. Since the camera is up in the air and the target is (most likely) on the ground, we
transform the camera's location to a position on the same horizontal plane as the
target. The targetLocation vector is pretty simple to handle. We just flatten it
by zeroing on the Y value as follows:
Vector3f targetLocation2D =
targetLocation.mult(UNIT_XZ);
6. The camera is a bit trickier; since we're interested in the target's position in relation
to the point the camera is looking at, we need to first find out where it is looking.
First, we get the relative position of the point the camera is looking at by multiply-
ing the height with the direction as follows:
Vector3f camDirOffset =
cam.getDirection().mult(camDistance);
7. Then, we add it to the camera's location (you can say that we project it on the
ground) to get its world position. Finally, we flatten this as well with UNIT_XZ as
follows:
Search WWH ::




Custom Search