Game Development Reference
In-Depth Information
To animate correctly, we have to know first whether the wheel is grounded. Therefore, we
define in line 51 a variable of type
WheelHit
, which gives us details about the state of the
wheel collider. The function
GetGroundHit()
returns
true
if the wheel collider is currently
grounded, and stores the details in
hit
by using the keyword
out
. The variable
hit.point
stores
the contact point between the wheel collider and the ground. Therefore, if we add the y
member of this point to the radius of the collider; we get the correct y value for the posi-
tion of the wheel. To keep thing simple, I am going to move the wheel in world coordinates
only. All we have to do is to update the y position of the wheel so it matches the current
center of the collider (lines 57 through 60).
In some cases, such as car jumping, the wheel collider does not touch the ground; which
requires us to return the wheel to its original position before applying the effect of the
suspension spring. If
GetGroundHit()
function returns
false
, then we know that the wheel is not
on the ground. In this case we return it smoothly to its original local position, which we have
already stored in
originalPos
. Smoothing transformations over several frames is essential for
acceptable animation, so we are going to learn how to implement it. The core function when
smoothing is the
Lerp()
function, which exists for a number of data types in Unity.
In this script we call
Vector3.Lerp()
, in order to smoothly return the wheel to its original
position.
Lerp()
function takes three arguments:
Vector3 from
,
Vector3 to
, and
float t
. If the
value of
t
is zero,
from
vector is returned, and if the value of
t
is 1,
to
vector is returned. If
t
= 0.5, the function returns the middle point between to vectors. We call this function in
line 64 and provide it with a small value (
Time.deltaTime
), so we get a new point on the path
between
transform.localPosition
and
originalPosition
. The returned point is closer to
trans-
form.localPosition
, so we store it in
pos
and use it as the new position of the wheel. As a
result, the wheel will keep moving smoothly towards
originalPos
, and eventually return to
its original position. Illustration 59 shows the difference between pressed and rest states
of the suspension springs. The final result can be found in
scene16
in the accompanying
project.