0
\$\begingroup\$

I can't do one of the simplest things. When the player taps the screen, I want to put my sprite in that place.

public class Controller : MonoBehaviour {

    public GameObject ball;  // A GameObject with a SpriteRenderer

    void Start () {

    }

    void Update () {
        if (Input.GetMouseButtonDown(0)) {
            ball.transform.position = Input.mousePosition;
        }
    }

}

Well, this doesn't work. When I tap the screen, the sprite appears further up and right. This is how the scene looks:

enter image description here

Where the sprite is by default at (0,0).

Aha, the problem seems quite obvious: if I touch the screen at (0,0) (the bottom-left), the sprite would appear at (0,0) - but as you can see, "(0,0)" is the center of the screen rather than the bottom-left, thus appearing further to the top and right as described above.

The solution seems pretty clear: the position of the sprite should be Input.mousePosition - new Vector3(Screen.width/2, Screen.height/2, 0) to make up for this offset! So:

ball.transform.position = Input.mousePosition - new Vector3(Screen.width/2, Screen.height/2, 0);

... It didn't quite work. Look, if I tap on the top-left of my screen, I get this:

enter image description here

If I tap on the bottom-right:

enter image description here

And if I tap on the center, it works correctly. But that's the only scenario.


How can correctly put my sprite wherever I tap on the screen?

\$\endgroup\$
2
\$\begingroup\$

Luckily, there's a method for this called Camera.ScreenToWorldPoint. You call it from a camera, pass a Vector3 where the x and y coordinates is the mouse position in pixels and z is the distance from the camera in world units. It then returns a world position as a Vector3.

In your example, you'd probably call it something like this:

const int DistanceFromCamera = 5;
ball.transform.position = Camera.main.ScreenToWorldPoint(Input.mousePosition + DistanceFromCamera * Vector3.forward);
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.