Graphics Reference
In-Depth Information
line of code is executed. If the time value is 0, the return value will be the start amount. If
time is 1, the return value will be the target amount.
By calculating the portion with Time.deltaTime, the transition from start value to
target value is smoothed out over a repeatable, fixed amount of time rather than it being
frame-rate dependent and based on how many times the Mathf.Lerp calculation line is
called:
currentHeight = Mathf.Lerp(currentHeight, wantedHeight,
heightDamping * Time.deltaTime);
Now that the script has calculated how much to rotate the camera and how high it
should be on the y -axis, the script goes on to calculate where the camera is going to go
position-wise.
wantedPosition is a Vector3 variable that will hold the target position. The first
target position is the target transform's position and an adjustment for height using the
currentHeight variable calculated above:
wantedPosition = target.position;
wantedPosition.y = currentHeight;
The next part of the code calculates how far behind the player we need to move the
camera. For this, the script uses Mathf.SmoothDampAngle. zVelocity represents the speed
of movement of the camera along its z -axis, but again it is purely a formality to use with
SmoothDampAngle and does not get used anywhere else in the script:
usedDistance = Mathf.SmoothDampAngle(usedDistance, distance,
ref zVelocity, distanceSnapTime);
To place the camera at the correct position around the target using only a rotation
angle, the solution lies within Quaternion.Euler. This rather frightening sounding func-
tion converts Euler angle Vector3-based rotations into a vector. That is, you pass in rota-
tion values and you get back a direction vector instead. Multiply this by how far back we
want the camera from the player, then add that to the player's current position, and we
have the correct rotation, position, and offset for the camera:
wantedPosition += Quaternion.Euler(0, currentRotationAngle,
0) * new Vector3(0, 0, -usedDistance);
myTransform.position = wantedPosition;
The final part of the function causes the camera to look at the target (player). It does
this by using Unity's built-in transform.LookAt() function. We pass in the position of the
target object (as a Vector3) and add an extra offset to where the camera is going to look, via
the lookAtAdjustVector variable. Note that you can also add an up vector to the LookAt()
function, but in this case we don't need to.
Aiming the camera directly at the player from behind the player may obscure the
path ahead and could make the game difficult to navigate. Instead, we add a small height
adjustment to the target position, so that the camera aims above the player as if it were
looking ahead, rather than right at it. With a simple target height adjustment, we can help
Search WWH ::




Custom Search