Problems with raycast

I’m using a script that another person helped me with to detect if the player is looking at an object that he can pick up and then picking it up. I’m using raycasts for this and it’s always been inaccurate as hell and i couldn’t find out why. So i debugged it with:

          		    if (Input.GetKeyDown(KeyCode.F))
					{ 
						Debug.DrawLine (ray.origin, hit.point, Color.red,2);
					}

and found that the line goes to 0,0,0 in the world instead of forward from where the camera is facing, picture shows the lines

[17335-red+lines.jpg|17335]

You can see I’m looking up but the lines still go down regardless of where i look.

The code i’m using is

public var crosshair : GUITexture;
var playerFlashlight : GameObject;
var player : GameObject;
var layermask : int = 8;
var cameraA : GameObject;

function Start () {

}

function Update () {
    var ray : Ray = cameraA.camera.ViewportPointToRay(crosshair.transform.position);

    var hit : RaycastHit;
          		    if (Input.GetKeyDown(KeyCode.F))
					{ 
						Debug.DrawLine (ray.origin, hit.point, Color.red,2);
					}
    
    if(Physics.Raycast(ray, hit, layermask))
   	{

  			if (hit.transform.name == "flashlight PICKUP" && Vector3.Distance(transform.position, player.transform.position) <= 3)
      		{

      		print ("YOU'RE HITTING IT");
      		    if (Input.GetKeyDown(KeyCode.E))
					{ 
      				playerFlashlight.GetComponent("LightScript").acquired = true;
      				playerFlashlight.GetComponent("LightScript").on = true;
      				Destroy (hit.transform.gameObject);
					}

    		}

	}  

}

I messed with layermasks to see if it was hitting the capsule but i don’t think that’s the problem based on the results of the line test.

If anyone has any ideas why this is happening it’d be helpful.
Thanks

You are calling your Debug.DrawLine() before you do the Physics.Raycast(). At that point in the code, ‘hit’ is uninitialized. In particular (since a RaycastHit is a struct), hit.point will be Vector3.zero. Insert lines 15 - 18 just inside the Raycast() at line 22. Then you will get a true reading of the what is going on:

BTW, I don’t see any problems with the Raycast() code. You might want to put the following line at line 22 so that you can see what the Raycast() is hitting. Often with Raycast() problems, the issue is the raycast either hitting things that the programmer did not expect or colliders that are not aligned correctly. The line:

Debug.Log(hit.transform.name+", "+hit.transform.tag);