Limit Rotation of an object

So basically I made an object rotate when I click and drag it but I want to limit the rotation to (50, -50) on the X axis, and (30, -30) on the Y axis. I tried a lot of things but nothing seems to work so far…
Here’s my code:
private void OnMouseDrag()
{
float XaxisRotation = Input.GetAxis(“Mouse X”) * rotationSpeed;
float YaxisRotation = Input.GetAxis(“Mouse Y”) * rotationSpeed;
transform.Rotate(Vector3.down, -XaxisRotation, Space.Self);
transform.Rotate(Vector3.right, -YaxisRotation, Space.Self);
}

(I will appreciate it if you help me.)
(If you can’t, is there a better way to rotate the object?)

2 Likes

Track the float angle yourself, adjust it, clamp it, then use it to drive the rotation.

transform.rotation = Quaternion.Euler( UpDownAngle, LeftRightangle, 0);

It might also suit you better to split the vertical and horizontal rotations into two separate parented transforms.

2 Likes

Yep, there is. Track your own X and Y rotations - that is, add your GetAxis results to a class-level variable. Then use transform.rotation = Quaternion.Euler(y,x,0) to set it. Once you’ve got that, you can easily Mathf.Clamp your tracked rotation values to anything you like.

Lots more information about rotations in Unity:

https://www.youtube.com/watch?v=HCZUwa3blQs

2 Likes

you can use the mathf.clamp method, like this

private void OnMouseDrag()
{
float XaxisRotation = Input.GetAxis(“Mouse X”) * rotationSpeed;
float YaxisRotation = Input.GetAxis(“Mouse Y”) * rotationSpeed;
XaxisRotation = Mathf.Clamp (, -maxX, maxX);

XaxisRotation = Mathf.Clamp (XaxisRotation.x, -50, 50);
YaxisRotation= Mathf.Clamp (XaxisRotation.x, -50, 50);

transform.Rotate(Vector3.down, -XaxisRotation, Space.Self);
transform.Rotate(Vector3.right, -YaxisRotation, Space.Self);
}

please test and let me know.

Without keeping track of the rotation per frame (as both replies before you said to do), this will only clamp the amount you can rotate every frame.

And will also give the OP at least… I’m counting 3 syntax errors?

And you didn’t use code tags.

2 Likes

I FINALLY DID IT WITHOUT CHANGING TOO MUCH ON MY CODE!!! I found a tutorial by Brackeys on how to do fps movement. Here’s the final code if anyone’s interested…

private void OnMouseDrag()
{
float XaxisRotation = Input.GetAxis(“Mouse X”) * rotationSpeed;
float YaxisRotation = Input.GetAxis(“Mouse Y”) * rotationSpeed;
XRotation -= YaxisRotation;
XRotation = Mathf.Clamp(XRotation, -40f, 40f);
YRotation -= XaxisRotation;
YRotation = Mathf.Clamp(YRotation, -40f, 40f);
transform.parent.localRotation = Quaternion.Euler(XRotation, -YRotation, 0f);

}

6 Likes

Thank you for this @KonniosGames - I was scouring the net looking for an answer to this very problem, and your code worked like a charm!

1 Like