Limited Rotate

Hello,
How can i add limit for accelerometer rotation? I want add 20 degree but I could not.

var xMinLimit = -20;
var xMaxLimit = 20;

function Update () {
     var tilt = Input.acceleration.x;
     tilt = Mathf.Clamp(tilt, xMinLimit, xMaxLimit);
     transform.Rotate(Vector3.forward * tilt * 2);
}

Ah yes in order to do this what I would use a Lerp or Slerp function.
So basically do this.

Create 2 Quaternions a min and max.
Then, because the expected input is between -1.0f and 1.0f we can then stream line the data. But, since Lerp or Slerp cannot take in a negative number, we need to then shift the number line over by 1 and divide by 2. So we have values between 0.0f and 1.0f. So between -20.0f and 20.0f the value will be 0.0f that is half way on the Lerp and Slerp functions so when they tilt toward -1.0f it will be getting closer to 0.0f meaning the rotation moves toward -20.0f and vise versa. So this is how you do it.

    Quaternion minRotation = Quaternion.Euler(new Vector3(0.0f, 0.0f, -20.0f));
    Quaternion maxRotation = Quaternion.Euler(new Vector3(0.0f, 0.0f, 20.0f));

    void Update() {
        Quaternion newRotation = Quaternion.Lerp(minRotation, maxRotation, (Input.acceleration.x + 1.0f) / 2.0f);
        this.transform.rotation = newRotation;
    }

Hope this helps

1 Like

Thank you very much Polymorphik. it worked.

If you want to have it be smooth just use and other Lerp function on this.transform.rotation so you have can have it be smooth transition

Thanks