Game Development Reference
In-Depth Information
12 ThisTransform = transform;
13 }
14
15 void
LateUpdate
()
16 {
17 //Billboard sprite
18 Vector3 LookAtDir = new Vector3 (Camera.main.transform.position.x - ThisTransform.
position.x, 0,
Camera.main
.transform.position.z - ThisTransform.position.z);
19 ThisTransform.rotation = Quaternion.LookRotation(-LookAtDir.normalized, Vector3.up);
20 }
21 }
Line 15.
The Billboard rotation code occurs inside
LateUpdate
and not
Update
.
Both events are called once each frame, so what's the difference? In short,
LateUpdate
is
always
called
after
Update
. This is important, especially for
cameras or objects that track the movement of other objects. For the Billboard,
our sprite rotates based on camera movement. If we rotate inside
Update
, it's
possible the Billboard
Update
will be called
before
the camera
Update
(that is,
before the camera is positioned and located physically in the game environment
for that frame)
. If that happens, then our Billboard rotation will be invalidated
because the camera will have moved since for that frame. If we use
LateUpdate
however, all update and movement functionality for the camera will have
finalized before rotating the Billboard, allowing us use the latest camera position.
Note
For more information on
LateUpdate
, see the online Unity documentation at
Line 18.
Here we use vector subtraction, subtracting the power-up position
(as a Vector3) from the camera position (as a Vector3) to produce a resultant
vector, expressing the difference between the two. This vector, in essence,
describes the
direction
in which the power-up would have to be looking to face
the camera. This line of code does not change the rotation of the sprite. It simply
calculates the direction in which the sprite
should
be looking.
Note
For more information on vector arithmetic, consult the Unity documentation at