I’m trying to limit the rotation of my object to 75 degrees to the left and 75 degrees to the right In the Z axis. At the start, the rotation.z is 0. rotating to the left yields values from 0 to 75 (at the moment 0 to 360 since it’s not limited yet). The part that confuses me is rotating to the right yields values from 360 to 285 (right now to 0 since not yet limited)
I know how to use Mathf.Clamp() but it seems that’s not enough in this case cause of the jump in values like that.
I’ve read up a few other similar questions regarding this and tried looking at the MouseLook script, but I couldn’t really figure out how to adapt it to my case.
This is my approach, hope it will help someone.
Just calculating future angle between the parent (tank, base etc) and the turret.
If angle is bigger that our max then turret is not beeing rotated.
In my case i was dragging to rotate an object with the mouse, so there was a lot of extra junk in there, but the main part is below. more to drag and have an axis (I believe i was using +x to point to where the mouse is)
private Vector3 origEuler;
Quaternion origRotation;
float RotateMin = 45f;
float rotateMax = 45f;
//Up in Start() we record our initial rotation..
origEuler = obj.transform.eulerAngles;
origRotation = obj.transform.rotation;
//down further, however you're figuring out what your rotation wants to be
//i was raycasting into a plane to get a target point
//targetDir was by targetPoint - obj.transform.position
Quaternion targetRotation = Quaternion.LookRotation(localAxis, targetDir);
//If there was a min max rotation value
if (rotateMin != 0 || rotateMax != 0)
{
//we make sure we stay within the limits with the euler angle
//(Assuming we're rotating in z here)
float difference = origEuler.z - targetRotation.eulerAngles.z;
if (difference < rotateMin && difference > -rotateMax)
obj.transform.rotation = targetRotation * origRotation;
}