I have a camera looking down on my game world. I want to allow the user to click on objects. The following script is attached to the MainCamera.
void Update () {
if (holdingSomething)
{
if (Input.GetMouseButtonUp(0))
{
holdingSomething = false;
}
}
else if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
Vector3 mousePos = new Vector3(Input.mousePosition.x,Input.mousePosition.y,0);
Vector3 rayOrigin = new Vector3(Camera.main.ScreenToWorldPoint(mousePos).x,Camera.main.ScreenToWorldPoint(mousePos).y,Camera.main.transform.position.z);
Vector3 rayDirection = new Vector3(Camera.main.transform.rotation.x,Camera.main.transform.rotation.y,Camera.main.transform.rotation.z);
Debug.Log("Mouse button is down" + mousePos);
Debug.Log("rayOrigin " + rayOrigin);
Debug.Log("rayDirection " + rayDirection);
Ray ray = new Ray(rayOrigin,rayDirection);
if (Physics.Raycast(ray, out hit))
{
Debug.Log("We just touched " + hit.collider);
}
}
}
The line Debug.Log("We just touched " + hit.collider);
is never called. I don't think my ray is being built right. Here is the output of the other debug messages. At each message they rayOrigin is the same, even though the mousePos changes.
Mouse button is down(418.7, 195.1, 0.0)
rayOrigin (0.0, 6.2, -7.3)
rayDirection (0.3, 0.0, 0.0)
Mouse button is down(417.7, 278.0, 0.0)
rayOrigin (0.0, 6.2, -7.3)
rayDirection (0.3, 0.0, 0.0)
So where am I going wrong?