# A little confused about scripting Raycasts

I’ve been working on a project for awhile involving alien ships attacking earth, and I’m currently trying to make it so that when the ships fire a laser at a building, the beam emits light onto the nearby surroundings. I’m using a script that measures the distance between the ship and the building and instantiates an appropriate number of point lights, and then places them an equal distance apart along the path of the beam.

Fairly straightforward, but I’m trying to write the script that instantiates the lights and places them along the beam’s path. The beam itself is a line renderer, but the position of each light is calculated using a raycast and the Ray.GetPoint(distance) function, along with a for loop that steps along the ray placing the point lights, if that makes sense.

If anyone particularly familiar with Raycast mechanics wouldn’t mind taking a look at the script I’ve got, the ray itself seems to want to start and stop at (0,0,0), or the world’s origin, regardless of where the ship or the laser are. I have some variables that print out for debugging purposes - they all seem to show what I’d expect them to show, except for "Ray: ", which, like I said, just prints out “Origin: 0,0,0 Direction: 0,0,0”.

I admit I’m not an expert at using rays, and I’m sure there are places in my script that can use some fine tuning - I’m not finished working out the details yet, I’m just trying to get the lights to show up where they’re supposed to. All I need is a point in the right direction, please. Thanks!

EDIT: By the way, this isn’t the full script, just the for loop that I mentioned.

``````for (var q = 1; q <= noOfLightsNeeded; q++)
{
var pointAlongRay : Vector3;
var ray : Ray;
var hit : RaycastHit;
var direction : Vector3 = laser.transform.position - target.transform.position;
if (Physics.Raycast (ray.origin, direction, hit))
{
print ("Origin: "+transform.position);
print ("Direction: "+direction);
print ("Hit: "+hit);
print ("Ray: "+ray);
Debug.DrawLine (ray.origin, hit.point);
pointAlongRay = ray.GetPoint(q);

if (noOfLightsNeeded > currentNoOfLights)		// Adds lights along the beam as necessary
{
Instantiate (laserGlowLight, pointAlongRay, transform.rotation);
currentNoOfLights++;
}

GameObject.Find("Laser Fire Glow(Clone)").transform.position = pointAlongRay;
}
}
``````

You created a ray variable, but you never defined it.

Set for your

ray.origin = ships.position

ray.direction =(building.position - ship.position)