Game Development Reference
In-Depth Information
Specifically, you'll be using Vector3.Lerp . Select it in the Scripting Reference for a quick
read-through.
Vector3.Lerp has three parameters: the from Vector3, the to Vector3, and a float value used in the
actual linear interpolation calculations.
First, declare a smoothing public float variable after the other variable declarations that you can use
to adjust the cube's movement from the Inspector:
public var smoothing : float;
Change your code in the Update() function for returning the cube to the origin as follows:
//move the cube back to the origin
if(Input.GetKey(KeyCode.O)) {
transform.position = Vector3.Lerp(transform.position, originPosition, smoothing *
Time.deltaTime);
}
Breaking down the key line of code, we see the following:
(1) (2) (3) (4) (5)
transform.position = Vector3.Lerp(transform.position, originPosition, smoothing *
(6)
Time.deltaTime);
1.
Sets the GameObject's Transform position,
smoothed with the Vector3.Lerp() function,
2.
3.
from the GameObject's current position,
4.
to the origin,
5.
with a smoothing multiplier we can use for customization,
6.
based on real time rather than varying frame rates.
Save and return to the Unity editor. With the Cube game object selected in the Hierarchy, in the
Inspector change the Smoothing property to 3. Enter Play mode. Now when you press and hold the
O key, the cube moves smoothly and in such a way that its movement becomes gradually slower the
closer it gets to the origin, ultimately coasting to a stop.
Now you've animated your primitive game object with a variety of movements in a number of
different ways. You've played games that effectively use simple motions like these for fun, interactive
experiences, but this only scratches the surface of what Unity can do. The remainder of this chapter
will give you an introduction to Mecanim, Unity's animation system, along with the wonderful variety
of characters and animation packs that can be found in the Asset Store.
Search WWH ::




Custom Search