Search code examples
unity-game-enginedraggabledrag

How can I limit draggable distance?


I tried to make a draggable drawer, I used this code:

     void OnMouseDrag() {
         Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
         Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;

         //Debug.Log(curPosition[0]);
         curPosition.y = gameObject.transform.position.y;
         curPosition.z = gameObject.transform.position.z;
         //curPosition.x = Mathf.Clamp(gameObject.transform.position.x,-3.0F,3.0F);
        transform.position = curPosition;

     }

How can I limit a drag range of x? Because I don't want to have something like this:

enter image description here

I tried to use Mathf.Clamp, but it doesn't work well.

Thank you! And sorry for my english.


Solution

  • I'd suggest using a Physics Joints, more preciselly a ConfigurableJoint. You can set a limit to the distance your joint can travel on each axis (I used it once to do some drawers).