# using Mathf.Clamp in Vector3 to restrict object drag

I'm making a checkers game and I've got a movement controller working to move the pieces. I want to restrict the drag to be within the board. The center of the board is 0,0 so the far left side's x value is -4, top of the boards y is 4, etc...

This is my drag script so far

void OnMouseDrag()
{
float distance_to_screen = Camera.main.WorldToScreenPoint(gameObject.transform.position).z;
transform.position = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, distance_to_screen));
}


but when I try to clamp my new Vector3's x and y between -4 and 4 like this,

transform.position = Camera.main.ScreenToWorldPoint(new Vector3(Mathf.Clamp(Input.mousePosition.x,-4f,4f), Mathf.Clamp(Input.mousePosition.y,-4f,4f), distance_to_screen));


it shoots the pieces way off camera. This may be because don't truly understand Camera.main.ScreenToWorldPoint, is it returning different x,y coordinates than the global ones?

Since your bounds (-4,-4) -> (4, 4) are world space coordinates, your error is that you're clamping the input (screen space) instead of the output of ScreenToWorldPoint.

Input.mousePosition will give you pixel coordinates between (0,0) and the max resolution of your screen (Screen.width, Screen.height).

Try clamping the result after the call to ScreenToWorldPoint:

void OnMouseDrag() {
float distance_to_screen = Camera.main.WorldToScreenPoint(gameObject.transform.position).z;
Vector3 before_clamp = Camera.main.ScreenToWorldPoint(new Vector3(
Input.mousePosition.x,
Input.mousePosition.y,
distance_to_screen));
transform.position = new Vector3(
Mathf.Clamp(before_clamp.x, -4, 4),
Mathf.Clamp(before_clamp.y, -4, 4),
before_clamp.z);
}

• Yup that was it, works perfectly. Thank you so much. – Andrew-Saarima Apr 26 '16 at 18:26