Gun shaking when it exceed the rotation limit

The gun just shakes when it comes to the point where it has to go to it’s previous rotation. How can I stop it being so jerky?

Code:

using UnityEngine;
using System.Collections;

public class GunPoint : MonoBehaviour
{
    private float rotX = 0.0f;
    private Quaternion oldRot = Quaternion.identity;

    public void Update()
    {
        rotX = Input.GetAxis("Mouse Y");

        if (transform.localRotation.x > -0.04f  transform.localRotation.x < 0.09f)
        {
            oldRot = transform.localRotation;
            transform.Rotate(-rotX, 0, 0);
        }
        else
        {
            transform.localRotation = oldRot;
        }
        // <= -0.04
        // >= 0.09
    }
}

Well. What I think is happening i that the gun rotates then immediate gets out of that “zone” that you described in you if statement, so it jumps back and the process repeats itself. Try adding some Slerp methods or something to smooth it out?

It is doing this because you rotate, then excede the number, then set the rotation back. You need to clamp the number. So its maximum value can only be x and minimum y. It is limited to them.

To do this though, you will need absolute control of your rotation.

Vector3 euler = transform.localEulerAngles;
euler.x -= Input.GetAxis("Mouse Y");
euler.x = Mathf.Clamp(euler.x, -0.04f, 0.09f);
transform.localEulerAngles = euler;

Thanks for that. It solved the problem.

Here still the problem! I’m trying to rotate in X and Y axis, +Y, -Y, -X is perfect but when use +x shake all!