Game Development Reference
In-Depth Information
if the boolean
movingBack
is true, then the normalized fractional amount
delta
is subtracted from
step
, otherwise
(8) else step += delta;
the normalized fractional amount
delta
is added to
step
.
(9) step = Mathf.Clamp01(step);
Mathf.Clamp01
is a function that “clamps” a value between 0 and 1 and returns a float value. In this
case, if
step -=delta
ever drops below 0,
Mathf.Clamp01
would simply return 0. If
step += delta
is
greater than 1,
Mathf.Clamp01
would simply return 1. For any value between 0 and 1,
Mathf.Clamp01
returns the same value.
(10) rigidbody.MovePosition(Vector3.Lerp(platformStartPosition,
platformEndPosition, step));
Instead of moving the platform game object by setting its Transform position,
Rigidbody.MovePosition
tells the physics engine to move the game object to the new position. By using the physics engine,
any other objects will be pushed aside according to their physical properties, maintaining consistent
behavior as this game object is moved. Using
Vector3.Lerp
smooths the movement of the game
object.
(11) if(step == 1.0f) movingBack = true;
Recall that if
movingBack
is
false
, the value of
step
is increased by the value of
delta
, then in
(9)
step = Mathf.Clamp01(step)
returns 1 if the value of
step
is equal or greater than 1. When
step
reaches the value of 1,
movingBack
is reassigned as
true
, so when the next
fixedUpdate()
call
reaches (7) the platform will begin to move in the opposite direction.
(12) else if(step == 0.0f) movingBack = false;
This is the reverse of (11). When
step
is decremented to 0 the boolean value of
movingBack
is
reassigned to
false
, so when the next
fixedUpdate()
call reaches (8) the platform will reverse
direction again. Save the script, attach it to the Platform 4 × 1× 4 game object, and Play. Try
changing
duration
and
lowLevel
until you feel it is a sufficiently challenging obstacle. Save the
scene and save the project (Figure
7-3
).