Game Development Reference
In-Depth Information
(5) line.SetPosition(0, ray.origin);
5.
The first point for the Line Renderer, Element 0, is set with the position of the
ray origin.
(6) line.SetPosition(1, ray.GetPoint(50));
6.
The second point for the line to be drawn to, Element 1, is set with the
position of 10 units further down along the ray.
That's a good start, but the laser is going straight through the elevated track, so it's not very realistic.
Edit the Laser script ShowLaser() function as follows:
function ShowLaser () {
var ray : Ray = Ray(transform.position, -transform.up);
var hit : RaycastHit;
line.SetPosition(0, ray.origin);
if(Physics.Raycast(ray, hit, 50))
{
line.SetPosition(1, hit.point);
} else {
line.SetPosition(1, ray.GetPoint(50));
}
}
Save the script. Now when you playtest, you'll see the laser stops at the surface of the track.
This code breaks down as follows:
(1) var hit : RaycastHit;
1.
Declare a reference variable hit of type RaycastHit.
(2) if(Physics.Raycast(ray, hit, 50))
2.
Test to see if the raycast detects a collider within 10 units.
(3) line.SetPosition(1, hit.point);
3.
If a collider is detected, set the second point for the line to be drawn where
the raycast detected the collider.
(4) } else {
line.SetPosition(1, ray.GetPoint(50));
4.
Otherwise, as before draw the line 50 units further along the ray.
For now the only thing to see is that the laser ends when it hits the track. By using a raycast, if any
other game object with a collider intersects the raycast, the laser will end wherever that intersection
occurs on the surface of the game object. To test this, playtest and put the player character in the
path of the laser beam.
 
Search WWH ::




Custom Search