Game Development Reference
In-Depth Information
The first thing this script does is storing the original (initial) position and rotation of the
block in
originalPos
and
originalRot
variables. Notice that rotation is stored in a variable
of type
Quaternion
. During
Update()
we scan for space key press. If it is pressed, we
call
Return()
function. This function simply sets
returning
flag to
true
, in order to let
the object move towards its original position in each frame. If
returning
is
true
, the object
must be moved towards
originalPos
and rotated towards
originalRot
. Before performing the
translation and rotation, we have to remove all forces and prevent them from affecting the
rigid body. Therefore, we ensure that the rigid body is frozen and clear all velocities affecting
it (lines 29 through 38). After that, we use
Vector3.Lerp
and
Quaternion.Lerp
to translate
and rotate the object smoothly. By multiplying
Time.deltaTime
by 3, we ensure a faster re-
turn. Finally, we find the remaining distance to reach the original position, if it is less than
0.01, we directly assign the original values of position and rotation to the transform. The
final result can be experimented in
scene19
in the accompanying project.