- Home /
The question is answered, right answer was accepted
How to get position of touch on touch screen
Hi, kind of new to unity android. Anyway i was wondering how i could get the position of a touch on the screen without it being in pixels cordinates. Here is the code I was trying.
if(Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
fingerPos = Input.GetTouch(0).position;
transform.position = fingerPos;
}
I had this attatched to a cube, and of course it flew off screen. Thanks for any help in advance!
What units do you want the co-ordinates in? If you want each axis as a 0 to 1 value you could calculate that by dividing by Screen.width and Screen.height.
yeah, but I wanted to get real x and y positions in space
Ok, if it's 2D you could use the camera's world position and offset it by the touch position. But assu$$anonymous$$g this is 3D, you'll probably want to use the 'picking' technique. If you touch the screen, the position in the world could be anywhere in the world along a direct, infinite line into the screen.
If you're not familiar with picking, you'll basically cast a ray from the touch position, directly into the screen until you hit the desired object. In that case, the world position will be the object's position. A good example you probably have seen in games is selecting a unit in a strategy game. You hover over a unit with a mouse and click, and it selects the unit. The mouse cursor isn't necessarily at the unit's position, it's just at some arbitrary point on the screen, but that's how you find what's directly under the mouse. The same logic applies to touch.
I've written a mouse picking script that would be very easy to adapt to touch if you're interested.
Answer by robertbu · Mar 20, 2013 at 06:08 AM
Since you are dealing with a perspective camera, the world coordinates will depend on the distance from the camera into the scene. So figure out the distance you want to use, then use Camera.ScreenToWorldPoint() to convert the value. For example, say you wanted it 8 units in front of the camera:
var pos : Vector3 = fingerPos;
pos.z = 8;
var realWorldPos = Camera.main.ScreenToWorldPoint(pos);
I add this because you said C#:
Vector3 pos = fingerPos;
pos.z = 8;
Vector3 realWorldPos = Camera.main.ScreenToWorldPoint(pos);
The Camera.main should be Camera.main. Other than that, great answer. Thanks for the help.
Follow this Question
Related Questions
how use specific for mobile button when we have 3 ? 1 Answer
Touch Not Working 0 Answers
multi touch / swipe issues 5 Answers
Make an Object follow your touch 0 Answers
Multiple Cars not working 1 Answer