Game Development Reference
In-Depth Information
function Update () {
transform.position = Vector3(Mathf.PingPong(Time.time * speed, 8) + offset,
transform.position.y, transform.position.z);
}
Save the script and attach it to the LaserCube.
This code breaks down as follows:
(1) public var speed : float = 1;
public var offset : float;
1.
First, declare variables: a public float variable that will allow you to adjust
the speed of the LaserCube from the Inspector, and an offset variable for
properly positioning the LaserCube as it moves.
(2) offset = transform.position.x - 0.2;
2.
In the Start() function, assign the position of the LaserCube game object
minus its width to offset so the laser beam starts at the exact edge of the
elevated track.
(3) transform.position = Vector3(Mathf.PingPong(Time.time * speed, 8) + offset,
transform.position.y, transform.position.z);
3.
You have changed the Transform.position of a game object before. This
example introduces using the Mathf.PingPong() function for the Vector3 x
coordinate value to get a back-and-forth movement.
Mathf.PingPong takes two floats, and returns a value that moves back and forth between 0 and
the second value, adjusted by the offset value and assigns the result to the x coordinate of the
LaserCube Transform.position.x . Without getting into the math behind it, the first float must
change with each frame to get the ping-pong movement, so Time.time is commonly used.
Time.time is simply the time in seconds since the game started.
Laser Beam
The laser beam is created with a Line Renderer. The Line Renderer cannot be used with a game
object that is already using a renderer, so best practice is to create an Empty game object to hold
the Line Renderer, then attach it as a child game object to the LaserCube.
In the editor top menu select Game Object ➤ Create Empty. In the Hierarchy, name it LaserBeam,
then drag it on top of the LaserCube game object to nest it as a child game object and give it a
Transform.position of (0, -0.5, 0). Since it is a child object, this Transform.position puts it slightly
below the parent LaserCube game object on the y axis. With the empty Game Object still selected,
in the Inspector select Add Component ➤ Effects ➤ Line Renderer (Figure 8-13 ). You will notice a
magenta line appear in the Scene view at the world origin. You will use a script for coordinating the
rendered line and the moving laser emitter during gameplay.
 
Search WWH ::




Custom Search