Game Development Reference
In-Depth Information
all of the defined axes in the input manager class, their bindings, their names, and
their parameters.
1. We compute the target direction vector for the character as proportional to
the user input (v, h). By transforming (v, h) into camera space, the result is a
world space vector that holds a camera relative motion vector that we store
in
targetDirection
as shown in the following code:
Vector3 targetDirection =
h * cameraRight + v * cameraForward;
2. If this target vector is non-zero (when the user is moving, and hence
v
,
h
are non-zero), we update
moveDirection
by rotating it smoothly (and by
a small magnitude), towards
moveTarget
. By doing this in every frame, the
actual direction eventually approximates the target direction, even as
tar-
getDirection
itself changes.
We keep
moveDirection
normalized because our move speed calculation
assumes a unit direction vector as shown in the following code:
moveDirection = Vector3.RotateTowards
(moveDirection, targetDirection,
rotateSpeed * Mathf.Deg2Rad *
Time.deltaTime, 1000);
moveDirection = moveDirection.normalized;
3. We smoothly LERP the speed of our character up and down, trailing the ac-
tual magnitude of the
targetDirection
vector. This is to create an appeal-
ing effect that reduces jitter in the player and is crucial when we are using
keyboard controls, where the variance in
v
and
h
raw data is at its highest,
as shown in the following code:
float curSmooth =
speedSmoothing * Time.deltaTime;
float targetSpeed = Mathf.Min
(targetDirection.magnitude, 1.0f);
moveSpeed = Mathf.Lerp
(moveSpeed, targetSpeed, curSmooth);