- Home /
What is the correct way to move an object to a target location?
So I have this ship sprite and I'm trying to get it to move to the position of the mouse when I click. The problem I'm having is that Input.mousePosition
returns the global position (exact coordinates of the mouse in the scren) like (1280;502) but when I try to make the ship move to that position by doing transform.position = Input.mousePosition
the ships goes off screen as it appairs that transform.position
uses some sort of relative position.
target = Input.mousePosition;
transform.position = target; //Anything bigger than 10 will make the ship go off screen
Answer by tanoshimi · Oct 18, 2014 at 06:34 PM
Input.mousePosition is in screen coordinates. You want to set transform.position in world coordinates. e.g.
if (Input.GetMouseButtonDown(0)) {
var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast (ray,hit)) {
transform.position = hit.point;
}
}
Thanks, I used:
Vector2 mousePos = Input.mousePosition;
Vector2 wantedPos = Camera.main.ScreenToWorldPoint(new Vector2 (mousePos.x, mousePos.y));
transform.position = wantedPos;
Answer by bubzy · Oct 18, 2014 at 06:04 PM
target = Input.mousePosition;
target.Normalize(); //you can multiply this if the results are too small.
transform.position = target;
It doesn't move off screen if I do that but it certain doesn't perform the way I expected; it appairs to just move a smaller amount to a random direction
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Trouble with null object reference. 2 Answers
How to convert to 2D 1 Answer
2D PlatformerController: Cumulative drift? 1 Answer
Replacement for LookAt in 2D 1 Answer