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

1 Answer

1

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.

Hello...Hi there. What if my camera is rotated?