Laser Beam using Raycasting & Line Renderer

Hello,

I am trying to us Line-Renderer to be able to see my Space-Ship shoot lasers, but when i do render the line it goes from the laser origin cube to the ship instead of the the actual target?

Raycast Code:

var laserOriginOne : GameObject;
var hitOne : RaycastHit;

function Update () {
if(Input.GetButton("Fire Laser")){
			if(Physics.Raycast(laserOriginOne.transform.position, Vector3.forward)){
			
			laserOriginOne.GetComponent(ShipFire).FireLasers(hitOne);
			
			Debug.Log(hitOne.transform);
			}
		}
}

‘FireLasers()’ Code:

var lineOne : LineRenderer;

function Start() {
	lineOne = GetComponent(LineRenderer);
	
	lineOne.enabled = false;
	
	lineOne.SetVertexCount(2);
	
	lineOne.SetWidth(0.1f, 0.25f);
}

function FireLasers(hitOne : RaycastHit){
	lineOne.enabled = true;
	lineOne.SetPosition(0, transform.position);
	lineOne.SetPosition(1, hitOne.point);
}

Like i said i don’t know why the laser goes from the ‘laserOriginOne’ to my ‘ship’?

I have tried a few thing such as moving my ship away from the laserOrigin blocks.

Thanks for any help!

You’re never setting the hitOne variable, so it stays all 0’s. That debug line should be showing you that. Change the raycast command so it does, by adding hitOne at the end:

Physics.Raycast(laserOriginOne.transform.position, Vector3.forward, hitOne))

Take a look at the script reference for Raycasts. It’s a little tricky – hitOne is an output parameter, which means it starts empty (like you have it) and is filled in by the ray cast. If you don’t send it, the ray cast doesn’t write the hit position anywhere.

There’s also probably a problem with using Vector3.forward for the direction. That will always shoot the laser due North. Just in general, you might want to browse through a bunch of other raycast examples here (shooting is a popular topic.) Raycasts use some tricky programming stuff.