Problem when dragging objects with mouse
Hello everyone. How you move an object with the mouse is a question that has been posted here many times, but after trying one of the solutions myself I got a problem I can't quite figure out. I was hoping you could help me out :)
This is the code (C#)
private Vector3 screenPoint;
private Vector3 offset;
void OnMouseDown()
{
screenPoint = Camera.main.WorldToScreenPoint(transform.position);
offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
}
void OnMouseDrag()
{
Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
transform.position = curPosition;
}
This is the problem: When I drag the object it does indeed move, but not together with the mouse... instead it only moves a part of the the way. For example: I drag the the mouse a distance from 1 to 10, but the object only moves from 1 to 3. This happens when I'm zoomed out from the object. The effect I'm after is for the object to be "glued" to the mouse pointer, to follow it exactly regardless of how far or close the camera is to the objects. Any ideas of what I'm doing wrong here? Any suggestions? :)
Thanks in advance.
Your answer
Follow this Question
Related Questions
How to know if the mouse has moved 0 Answers
Rotate and scale sprite based on mouse position 0 Answers
HOW TO MOVE ANIMATED OBJECT ON CANVAS 0 Answers