Game Development Reference
In-Depth Information
if(Input.GetKey(KeyCode.RightArrow)) {
transform.Rotate(Vector3.up * -rotationSpeed * Time.deltaTime);
}
}
Save and play.
Translate
Translate() is another function of Transform, used for moving the GameObject. Like Rotate() ,
it also takes a Vector3 argument, but in this case the Vector3 describes the direction and distance of
GameObject movement to take place. Add a public variable you can use as a multiplication factor to
adjust the speed of the cube in the editor. Underneath the rotationSpeed variable declaration, add a
travelSpeed variable.
public var travelSpeed:float = 5;
Let the player move the cube up and down with the up and down arrows by adding the following
lines of code to the Update() function.
if(Input.GetKey(KeyCode.UpArrow)) {
transform.Translate(Vector3.up * Time.deltaTime * travelSpeed);
}
if(Input.GetKey(KeyCode.DownArrow)) {
transform.Translate(Vector3.down * Time.deltaTime * travelSpeed);
}
Save and play. This time, rather than using -travelSpeed for the down direction, you used
Vector3.down . Either would have worked, just as -Vector3.up is also equivalent to Vector3.down .
There is often more than one way to get the same result; it's largely personal preference. If you have
a choice, opt for the most efficient code and if all else is the same, the more readable the better.
Transform.position
Whereas Translate() is a function that moves the transform, position is a variable holding the (x, y, z)
values of the position of the transform. You can also move the GameObject to a specific location by
simply assigning a new position. In this example, we'll use the O key to send the GameObject back
to the origin (0, 0, 0).
First, add a new private variable declaration underneath the public variable declarations.
private var originPosition : Vector3 = new Vector3(0, 0, 0);
In the Update() function, add the following:
if(Input.GetKey(KeyCode.O)) {
transform.position = originPosition;
}
 
Search WWH ::




Custom Search