- Home /
Casting a ray to detect the touched object in world space does not work
I am trying to determine the object that I touch on the iPhone by casting a ray from the camera position to the touched position on the screen. It does not work. When I dray the ray as a Gizmo, I can see the ray moving outside the game region and also into opposite directions as if the scale and orientation are wrong. What am I doing wrong? Below is the script:
function OnDrawGizmos(){ Gizmos.color = Color.blue; var touch : iPhoneTouch; if (iPhoneInput.touchCount > 0) { touch = iPhoneInput.GetTouch(0); pos = touch.position; var ray : Ray = Camera.main.ScreenPointToRay(Vector3(touch.position.x, touch.position.y)); var hit : RaycastHit; if (Physics.Raycast(ray,hit)) { Gizmos.DrawCube (hit.point, Vector3(1,1,1)); }
Gizmos.DrawRay (ray.origin, ray.direction * 100);
}
}
Answer by Tetrad · Jun 07, 2010 at 03:58 PM
Try using Input.mousePosition instead of getting the position of the touch. If that works, then you know that it's a coordinate system error. ScreenPointToRay and Input.mousePosition both assume (0,0) is in the bottom left. I don't know off the top of my head what iPhoneTouch.position uses.
Answer by shaystibelman · May 17, 2012 at 10:21 AM
I think it's because you're using a Vector3 instead of a Vector2:
var ray : Ray = Camera.main.ScreenPointToRay(Vector3(touch.position.x, touch.position.y));
should be:
var ray : Ray = Camera.main.ScreenPointToRay(Vector2(touch.position.x, touch.position.y));
Your answer
![](https://koobas.hobune.stream/wayback/20220613055308im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
iPhone touch raycasting 1 Answer
Joystick Raycast Problem? 2 Answers
unity touch is not working properly 1 Answer
How do Iake an object touch interactive 1 Answer
Unity UI: neglect transparent area of button and trigger user input underneath it. 2 Answers