Game Development Reference
In-Depth Information
Once these distances have been defined, we need to track the position of the character in
each update iteration to test if we should move the camera. First of all, notice that in line 22
we have called LateUpdate() function instead of Update() which we used to use previously.
These functions are both called once every frame. It is guaranteed, however, that Unity will
call Update() first from all scripts in the scene, then it will go through all scripts again and
call LateUpdate() . In other words, it is guaranteed that the code in LateUpdate() is always
executed after the code in Update() in any given update iteration.
Keep in mind that we have two scripts in the current scene: PlatformerControl which reads
player input and performs character movement, and PlayerTracking which allows the cam-
era to follow the character. Now we want to be sure that character movement completes
before the camera moves. The easiest way to do that is to update camera movement from
LateUpdate() function. This ensures that character movement is completed and the character
is now in the new position, before the camera moves. Notice that if you use Update() for
PlayerTracking instead of LateUpdate() , you might be lucky to have Unity call Update() from
PlatformerControl first and then from PlayerTracking , hence you get a correct behavior.
However, in programming we do not let luck control anything, and we always count for the
worst case scenario.
As you see in lines 24 and 26, we start by storing the positions of both the camera and the
character, in order to perform the required computations between them. After that we start
to check for possible cases on the x axis. Th s checking takes place in lines 30 through 36.
Keeping in mind that the positive direction of the x axis is to the right, we subtract x position
of the camera from the x position of the character. If the result is greater than right limit defi
ed by maxDistanceRight , we move the camera to follow the character.
Search WWH ::




Custom Search