Reputation: 1573
I am making a script to drag an object on Y axis. It is almost done, but I have one problem. When I click the object, center of object moves to the mouse position, and then I drag it like that so the center is always on mouse position. How can I make when I hold for example bottom of the sprite, center of sprite stays where it is and it doesn't move to the mouse position? Here is my script:
public Vector3 screenPoint;
public Vector3 offset;
void OnMouseDown(){
screenPoint = Camera.main.WorldToScreenPoint (gameObject.transform.position);
offset = gameObject.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 = new Vector3(transform.position.x, curPosition.y, transform.position.z);
}
Thank you.
Upvotes: 0
Views: 1429
Reputation: 3277
It's because your curScreenPoint
is still in pixel coordinates. The one you did in OnMouseDown
was correct. So you should also convert the pixel coordinates in OnMouseDrag
to screen space:
Change this line:
Vector3 curScreenPoint = new Vector3(Input.mousePosition.x,
Input.mousePosition.y,
screenPoint.z);
To this:
Vector3 curScreenPoint = Camera.main.ScreenToWorldPoint (new Vector3 (
Input.mousePosition.x,
Input.mousePosition.y,
screenPoint.z)
);
Also I don't quite understand what you're doing in this line:
Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint), offset;
But it should be like this since you only want to move the Y:
Vector3 curPosition = new Vector3(curScreenPoint.x,
curScreenPoint.y + offset.y,
curScreenPoint.z);
Upvotes: 1