- Home /
[2D Mode] Trying to make a sprite dragable
I have setup 4.3 in 2D mode and I'm trying to simply drag a sprite on click.
I was under the impression the coordinates I need would be from Camera.main.ScreenToWorldPoint(Input.mousePosition) So I have:
void Update(){
Debug.Log (Camera.main.ScreenToWorldPoint(Input.mousePosition).ToString());
}
void OnMouseDown(){
transform.position = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
But this doesn't work, infact the position returned by Camera.main.ScreenToWorldPoint(Input.mousePosition) is always (0.0, 1.0, -10.0) no matter where the mouse is.
Any ideas?
EDIT: Solved it
Screen to world wants a vector3 and technically I was supplying only 2 dimensions, although it ran... You need to separate mouse x and y and then supply z which is the distance of the object from the camera. Also OnMouseDrag is obviously better for drag functionality
New code looks like this:
public class ButtonClick : MonoBehaviour {
float x;
float y;
// Update is called once per frame
void Update(){
x = Input.mousePosition.x;
y = Input.mousePosition.y;
}
void OnMouseDrag(){
transform.position = Camera.main.ScreenToWorldPoint(new Vector3(x,y,10.0f));
}
}
Thanks man, my sprite was disappearing b/c of the z value!
please cut & paste your solution as an answer, then mark it as accepted. It helps keep our answers site tidy and avoids the buildup of unanswered questions!
Indeed, I'd hoped OP had also left a comment. I would have done this for him.
Your answer
Follow this Question
Related Questions
Drag and Drop w/ Snapping 0 Answers
how i can drag a sprite in 2D mode?? 1 Answer
How can I achieve this particular 2D lighting effect? 2 Answers
2D LookAt not working as intended 1 Answer