Game Development Reference
In-Depth Information
From here you'll need a script to control the behavior of the laser. In the Project panel Assets ➤
Scripts folder, select Create ➤ JavaScript, name it Laser, and open it in MonoDevelop. Edit the code
to the following:
#pragma strict
public var line : LineRenderer;
function Start () {
line = gameObject.GetComponent.<LineRenderer>();
}
function Update () {
ShowLaser();
}
function ShowLaser () {
var ray : Ray = Ray(transform.position, -transform.up);
line.SetPosition(0, ray.origin);
line.SetPosition(1, ray.GetPoint(50));
}
Save the script, attach it to the child empty game object, and playtest. You'll see that the LaserCube
moves side to side, emitting a red laser.
This code breaks down as follows:
(1) public var line : LineRenderer;
Declares a reference variable line of type LineRenderer .
1.
(2) line = gameObject.GetComponent.<LineRenderer>();
Gets the reference to the Line Renderer component and assign it to the line
variable.
2.
(3) ShowLaser();
3.
In previous examples the code samples have been largely written in the
Update() function. With this example, better code writing practices are
employed, where the code is broken down into smaller modules. Here the
ShowLaser() function that contains just the laser-drawing code is called.
(4) var ray : Ray = Ray(transform.position, -transform.up);
Within the ShowLaser function, a reference variable Ray is created and
assigned the game object's transform.position as its origin and
-transform.up for a downward direction.
4.
 
Search WWH ::




Custom Search