0
\$\begingroup\$

How do I rotate the object only once after a key press. So after it rotates say 10 degrees upwards, the user can't rotate it anymore.

this is my code which as continuous rotation -:

   void Update(){
 if (Input.GetKey(KeyCode.J))
     transform.Rotate(0, 0, 3f);
  }
\$\endgroup\$
2
\$\begingroup\$

Add a private bool isRotated variable to the script. This variable stores the information if the user did already rotate this object or not.

Then check that variable in your code.

 if (Input.GetKey(KeyCode.J) && isRotated == false)
     transform.Rotate(0, 0, 3f);
     isRotated = true;
  }

Another solution might be to disable or even destroy the component which handles the rotation of the object. But that's of course only an option when the component only handles the rotation and nothing else.

\$\endgroup\$
2
\$\begingroup\$

@Philipp's answer is correct but I want explain more about limiting

if you want rotate the object only once after a key press you should use Input.GetKeyDown In Update function

but if you want limit rotation between two value min_max you can use Mathf clamp

function clamp(x, min, max):

if (x < min) then x = min; else if (x > max) then x = max;

return x;

end clamp

Mathf.Clamp(float value, float min, float max);

using UnityEngine;
using System.Collections;

public class RotationController : MonoBehaviour {

    void Update () {
        transform.rotation = Quaternion.Euler(new Vector3 (
            transform.rotation.eulerAngles.x,
            transform.rotation.eulerAngles.y,
            Mathf.Clamp (transform.rotation.eulerAngles.z, -3, 3)));

        if (Input.GetKeyDown(KeyCode.D))
            transform.Rotate(0, 0, 3);
        if (Input.GetKeyDown(KeyCode.A))
            transform.Rotate(0, 0, -3);
    }
}

in other way you can use Quaternion to limiting Quaternion definition:

using UnityEngine;
using System.Collections;

public class degree : MonoBehaviour {
  public float w,x,y,z;
  public float a = 0;


  void Start(){
    a = a / 360 * (float)Mathf.PI * 2;
    w = Mathf.Cos (a / 2);
    x = Mathf.Sin (a / 2);
    y = Mathf.Sin (a / 2);
    z = Mathf.Sin (a / 2);
    print (a);
    gameObject.transform.rotation = new Quaternion (w,x,y,z);
  }
}

you should know about Degrees 30° Radians(exact)π/6 Radians(approx) 0.524 learning link

so you can limit rotation:

void Update () {
    print (transform.rotation.z);
    if (Input.GetKeyDown(KeyCode.D) && transform.rotation.z <0.02617695)
        transform.Rotate(0, 0, 3);
}
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.