Game Development Reference
In-Depth Information
In the Hierarchy view, select Create ➤ Cube. Unity's primitive object cube will appear in the Scene
view at (0, 0, 0).
In the Inspector view, select Add Component ➤ New Script, name it MoveCube, and make sure the
Language property is JavaScript. Click the Create and Add button to see it appear as a component
in the Inspector. In the Project panel, the script appears in the Assets root folder. To keep your
project organized, move it to the Scripts folder.
Now open up MoveCube in MonoDevelop. To get the illusion of movement, you want Unity to
render the cube in a slightly different position in each frame, which means that you want to use the
Update() function. In the Update() function between the curly braces, add the following line of code:
transform.Rotate(Vector3.up); . Save the script, click Play to test, and your cube is rotating—yay!
Let's break down this line of code in order to understand what is going on here:
(1) (2) (3) (4)
transform.Rotate(Vector3.up);
1.
Transform is the one mandatory component for every game object; it
holds its position, rotation, and scale information. In this line of code, you
can use transform here with a small t and the compiler knows that this
means the Transform component of the game object to which this script is
attached. Affecting the Transform component of one game object from a
script attached to a second game object is slightly more involved and will be
covered beginning in Chapter 6, Accessing Other Game Objects.
Rotate() is a function of the Transform class. You can +' to read the
Scripting Reference. It applies a rotation around the axis of its Vector3
parameter in Euler angles. Euler angles is an advanced mathematical term
regarding the rotation in degrees around the game object's axes.
2.
3.
The Vector3 parameter defining the axis around which the rotation will take place.
4. .up is the Vector3 static variable shortcut for the vector (0, 1, 0).
Take a closer look at the cube's translate gizmo and remember that the y axis is “up” in
Unity's world space. Play again to confirm visually that the cube rotation is occurring around
the y axis. Take a look at the Inspector, and you can see the y value of the rotation property of
the Transform component is changing in accordance with the changing rotation of the cube
(Figure 5-2 ).
 
Search WWH ::




Custom Search