I’m trying to figure out how I can get the position of a touch to select an object, however I’m a bit stumped. I’m using this as a starting point:
foreach(Touch t in Input.touches)
{
Vector3 wp = Camera.main.ScreenToWorldPoint(new Vector3(t.position.x, t.position.y, 0));
Debug.Log (wp.ToString());
}
However, the wp is the exact same position of the main camera no matter where I tap the screen. I’m obviously missing something, but I can’t seem to figure it out. Any help would be great! Thanks!
1 Answer
1
Your code above will work for an Orthographic camera. You can simplify it a bit by:
Vector3 wp = Camera.main.ScreenToWorldPoint(t.position);
But given your reported issue, you must be using a Perspective camera. To fix the problem you need to set the ‘z’ parameter to the distance in front of the camera to calculate the point. The world position will vary based on the distance. So you can do:
Vector3 wp = Camera.main.ScreenToWorldPoint(new Vector3(t.position.x, t.position.y, dist));
…where ‘dist’ is the distance in front of the camera to do the calculation.
I should also mention that this is for a 2D game.
– Benjaben22