Transform tr; void Start () { tr = transform; } void Update () { if(Input.touchCount > 0) { foreach(var th in Input.touches) { tr.position = new Vector3(th.position.x, th.position.y, 0); ; } } } 

The task is simple - you need to follow the finger object. The code is hanging on this object. The problem is this - at different screen resolutions the code works in different ways! Even a banal screen flip shifts the object 200 pixels left and up, i.e. it follows not a finger, but a point that is higher and to the left of the finger. When the screen resolution is the same story. Ortho camera, lower left corner of the camera at coordinates 0,0,0. What is the matter, I can not understand. Is there a simple replacement for this code so that the object simply repeats the coordinates of the finger, pixel to pixel?

    1 answer 1

    Most likely you need to convert the coordinates of clicking into the coordinates of a point in the game.

    You can try to use Camera.ScreenPointToRay - returns the beam coming from the camera through a point on the screen.

    Those. for example we have one click

     var touch = Input.GetTouch(0); 

    Convert it

     var ray = Camera.main.ScreenPointToRay(touch); 

    The position will be stored in origin , i.e. ray.origin.x and ray.origin.y

    Those. in fact transform.position = ray.origin; because and transform.position and ray.origin this is Vector3

    those. there will be something like this:

     foreach(var th in Input.touches) { var ray = Camera.main.ScreenPointToRay(th); tr.position = new Vector3(ray.origin.x, ray.origin.y, 0); // tr.position = ray.origin; } 

    If ScreenPointToRay fails , you can try your luck with Camera.ScreenToWorldPoint . There will no longer be the origin , the method converts the position (position) from the screen space to the world space and immediately returns Vector3.

    • Thank! A couple of questions! And how can I do this with pixels, without conversion? Are there any camera settings in Unity that always have touchscreen coordinates equivalent to coordinates on the screen? If done through Ray, wouldn't it be more demanding on resources? - Dmitrii
    • one
      @Dmitrii I do not know. I think ScreenPointToRay centers the coordinate, because the plane of depression is large. Ray is often used in 2v platformer to determine the distance to the subject. Moreover, they do it in such a way that from each side from 3 to 10 rays are produced for accuracy. So if it is not planned that dozens of fingers will be pressed simultaneously, and 1,2,3 - that is quite. - Alexey Shimansky