This recipe will cover some principles on how to make the camera follow something in the game world. While it might seem like an easy task at first, there are some tricky bits too.
The recipe will build upon the Creating an RTS camera AppState object recipe of this chapter. All of the steps described in this recipe will be applied to AppState
.
To make the camera follow units, perform the following steps:
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.UNIT_XZ
, which we set to(1f, 0, 1f)
. We'll use this to convert 3D positions to 2D.update
method just before cam.setLocation(camLocation);
.if(tempVector.length() > 0){ follow = false; }
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);
Vector3f camDirOffset = cam.getDirection().mult(camDistance);
UNIT_XZ
as follows:Vector3f camLocation2D = camLocation.add(camDirOffset).multLocal(UNIT_XZ);
if(targetLocation2D.distance(camLocation2D) > 0.01f){ camLocation2D.interpolate(targetLocation2D, 0.3f); camLocation.set(camLocation2D); camLocation.subtractLocal(camDirOffset);
worldTranslation
and not localTranslation
in this case:appState.setTargetLocation(jaime.getWorldTranslation()); appState.setFollow(true);
update
method of the test case, we make him slowly move along the x axis as follows:jaime.move(0.2f * tpf, 0, 0);
Another way of handling it would be not to move the camera during the input but the actual point it looks at, and have the camera troll along. No matter which way you choose to do it though, practicing and thus getting a better understanding of these trigonometric problems is always a good idea.
Since we're using linear interpolation here, camLocation2D
will never actually reach targetLocation
; it'll just get infinitely closer. This is why an if
statement can be useful in these cases to see whether it's worth actually changing the distance or not. Finding the right threshold to break off is empiric and varies from case to case.
3.141.31.125