Game Development Reference
In-Depth Information
In Unity, Z is considered “forward.”
Add the following lines to the Update function:
3.
// Move the object forward along its z axis 1 unit/frame
transform.Translate(Vector3.forward);
4.
Save the script, and click Play.
The bench quickly scoots out through the gateway. Let's slow it down.
Change the transform line as follows:
5.
transform.Translate(Vector3.forward * 0.1f);
The transform.Translate() function expects floats for its argument, so you must add the f to the
speed adjustment.
6.
Save the script, and click Play.
The bench isn't in quite as much of a hurry to leave the scene this time. But the problem is that it
is moving 0.1 units per frame . And frame rate varies throughout a game and from device to device.
You could put the code in a FixedUpdate function to ensure a constant speed across platforms and
throughout the game, but a more common solution is to use Time.deltaTime . This essentially tells
the engine to divide the task so that it uses seconds rather than frames. The variable deltaTime is a
member of the Time class, so Time (the first one) is capitalized.
Change the transform lines as follows:
7.
// Move the object forward along its z axis 1 unit/second
transform.Translate(Vector3.forward * Time.deltaTime);
8.
Save the script, and click Play.
The bench moves at a nice stately pace and heads out the gateway. Typically, though, speed is
something that is exposed to let the author adjust at will. Where you had a float number earlier, you
can add a variable.
1.
Create the new speed variable beneath the counter variable:
public float speed = 0.5f;
This one is public, so it will be exposed to the Inspector.
Change the transform lines as follows:
1.
// Move the object forward along its z axis 1 unit/second * speed.
transform.Translate(Vector3.forward * Time.deltaTime * speed);
Before you test, remember that most number fields in Unity usually have slider functionality. By
positioning the cursor in front of the text box or over its label, you will see the cursor change to
include a couple of horizontal arrows. At that point, you can mouse down and move the mouse left
and right to increase or decrease the value quickly.
 
Search WWH ::




Custom Search