Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Limited Rotate

Discussion in 'Scripting' started by mrttis, Aug 7, 2015.

  1. mrttis

    mrttis

    Joined:
    Jul 12, 2012
    Posts:
    64
    Hello,
    How can i add limit for accelerometer rotation? I want add 20 degree but I could not.

    Code (JavaScript):
    1. var xMinLimit = -20;
    2. var xMaxLimit = 20;
    3.  
    4. function Update () {
    5.      var tilt = Input.acceleration.x;
    6.      tilt = Mathf.Clamp(tilt, xMinLimit, xMaxLimit);
    7.      transform.Rotate(Vector3.forward * tilt * 2);
    8. }
     
  2. Polymorphik

    Polymorphik

    Joined:
    Jul 25, 2014
    Posts:
    599
    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.

    Code (CSharp):
    1.     Quaternion minRotation = Quaternion.Euler(new Vector3(0.0f, 0.0f, -20.0f));
    2.     Quaternion maxRotation = Quaternion.Euler(new Vector3(0.0f, 0.0f, 20.0f));
    3.  
    4.     void Update() {
    5.         Quaternion newRotation = Quaternion.Lerp(minRotation, maxRotation, (Input.acceleration.x + 1.0f) / 2.0f);
    6.         this.transform.rotation = newRotation;
    7.     }
    Hope this helps
     
    mrttis likes this.
  3. mrttis

    mrttis

    Joined:
    Jul 12, 2012
    Posts:
    64
    Thank you very much Polymorphik. it worked.
     
  4. Polymorphik

    Polymorphik

    Joined:
    Jul 25, 2014
    Posts:
    599
    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
     
  5. mrttis

    mrttis

    Joined:
    Jul 12, 2012
    Posts:
    64
    Thanks