Weird raycast problem with hit.point

Hi All,

I have a problem with raycasting and I can’t figure out what the problem is. I have a beam that shoots at another ship. I cast a ray to see if it hits the enemy shield. If it does, the beam position is set to the hit.point.

For some reason, the hit.point does not coincide with what it should be.

The hit.point should be at where the blue line hits the shield, but it is not happening.

function Update () 
	{
		if(active_beam != null) //is a beam being fired? 
		{
			//check if there is an object blocking the beam
			var hit : RaycastHit;
			var layerMask = 1 << 12;
			var hit_pos : Vector3 = target_ship.transform.position + target_pos;
			
			Debug.DrawLine (beam_source.transform.position, hit_pos, Color.blue);
			
			if(Physics.Raycast(beam_source.transform.position, hit_pos, hit, Mathf.Infinity, layerMask)) 
			{
				active_beam.GetComponent(LineRenderer).SetPosition(1, hit.point);
			}		
			else
			{
				active_beam.GetComponent(LineRenderer).SetPosition(1, hit_pos);
			}
			
			//move targetpos towards end_pos
			if(target_pos != end_pos)
			{
				target_pos = Vector3.MoveTowards(target_pos, end_pos, Time.deltaTime * beam_speed);
			}
			
			//set the active beams linerenderer positions
			active_beam.GetComponent(LineRenderer).SetPosition(0, beam_source.transform.position);	
		}
}

what is “target_pos”? where is that initially set?

I can see the update later on in the code, but at line 8 we don’t know what it is set as.

Fixed it. Apparently raycasts were not the way to go. I used Physics.Linecast and now it works perfectly.

Thanks for the help though.

Raycast are fine… Just that you are not using a ray direction properly.

No, I know now, but Linecast works better here anyway, since there is no need to go beyond the targetship anyway.