Physic Raycast ?

Hello everybody.

I am trying to use a raycast to get the world position of a game object with the following script, attached to my main camera :

#pragma strict

private var hitPos		: Vector3 ;
private var hitObjectPos 	: Vector3 ;

function Update(){

	if (Input.GetMouseButtonDown(0))
	{
		Debug.Log("Pressed left click.");
		var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition) ;
		var hit : RaycastHit;
	
		if (Physics.Raycast (ray, hit, 100))
		{
			Debug.Log("Physics Raycast ok.");
			Debug.DrawLine (ray.origin, hit.point);
			hitPos = hit.point ;
			hitObjectPos = hit.transform.position ;
			Debug.Log("World position : "+hitObjectPos);
		}
	}
}

The message “Pressed left click.” is correctly printed on the console, but not the following messages. Notice that I have added a collider to my game object :

Have you an idea of what I have forgotten or done wrong ?

Thank you for reading.

Your collider is of type Collider2D and your raycast is using Unity’s 3D physics engine. You will will have similar issues when trying to get Collider2Ds to collide with normal 3D Colliders.

Try using

Physics2D.Raycast(ray, hit, 100)

I changed my 2d collider to a 3d collider, and now it works perfectly !
I use the following code to get cleaner coordinates :

 #pragma strict
 
 private var pos : Vector3 ;
 
 function Update(){
 
     if (Input.GetMouseButtonDown(0))
     {
         var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition) ;
         var hit : RaycastHit;
     
         if (Physics.Raycast (ray, hit, 100))
         {
             pos = hit.transform.position ;
             Debug.Log("World position : ("+pos.x+","+pos.y+")");
         }
     }
 }

Thank you very much for your help. :slight_smile: