- Home /
Question by
$$anonymous$$ · Jan 31, 2014 at 02:45 AM ·
c#dragboundary
c# Object Drag ScreenToWorldPoint Limits
Hello, I'm using the following code to allow my 'player' to be dragged around the screen in a 2d game. I would like to impose boundaries so the player cannot be dragged out side of the screen. I couldn't find anything on this, any help?
private Vector3 screenPoint;
private 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 = curPosition;
}
Thanks.
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220613132137im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Dragging an object smoothly 2 Answers
What's the difference between MonoBehavior OnMouseDrag and IDragHandler OnDrag 1 Answer
Check any DragEvent on scene 0 Answers