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:
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:
If I tap on the bottom-right:
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?