Niana Niana - 3 months ago 22
C# Question

Move player to exact touch/mouse click location

I am newly working on a 2D unity game and im not understanding what is happening.


I am trying to move my sprite to the location of my touch (right now it's a mouse click).

My sprite is at location X 173, Y 48, Z -52.1 .
However, when I click a location that is probably a few pixels away my position is changed to (399.0, 129.0, 0.0) and my sprite is apparently hurled into the vast unknown.

if (Input.GetMouseButtonDown(0))

//fingerPos = Input.GetTouch(0).position;
fingerPos = Input.mousePosition;
transform.position = fingerPos;

Any help with this would be appreciate. Thank you


transform.position is in world coordinates. Input.mousePosition returns values in pixel coordinates. You need to convert this into world coordinates.

fingerPos = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position); //Mobile
fingerPos = Camera.main.ScreenToWorldPoint(Input.mousePosition); //Desktop

Then you can assign it to your position.

transform.position = fingerPos;