Search code examples
c#unity-game-enginerotatetransform

How to set a max rotation on an object in C# (Unity)


I am trying to make a space ship tilt upwards when it travels upwards or tilt downwards when it falls but I'm stuck this is what I have so far

 if (Input.GetKey(KeyCode.Space)) //If spacebar pressed
        {
            playerRb.AddForce(Vector3.up * floatForce, ForceMode.Impulse); // Add force upwards to player
        }

        // Rotates upwards
        if (Input.GetKey(KeyCode.Space))
        {
            if (transform.rotation.x != -maxRotation)
            {
                transform.Rotate(-rotationSpeed, 0f, 0f * Time.deltaTime);
                transform.Rotate(-maxRotation, 0f, 0f);
            }
        }

It just spins infinitely when I press down on the space bar...

Any help? Thank you


Solution

  • If you want to limit rotation of an object, you can modify the eulerAngles property value.

    Example

    The following script takes a couple of vectors and makes sure the object rotation remains in range between their x, y, z values.

    using UnityEngine;
    
    public class RotationLimitter : MonoBehaviour
    {
        [SerializeField]
        private bool runOnUpdate = true;
        [SerializeField]
        private bool runOnLateUpdate = false;
        [SerializeField]
        private bool runOnFixedUpdate = false;
        
        [Space]
        [SerializeField]
        private Vector3 minRotation = Vector3.zero;
        [SerializeField]
        private Vector3 maxRotation = Vector3.zero;
    
        private void Update()
        {
            if (runOnUpdate)
                LimitRotation();
        }
    
        private void LateUpdate()
        {
            if (runOnLateUpdate)
                LimitRotation();
        }
    
        private void FixedUpdate()
        {
            if (runOnFixedUpdate)
                LimitRotation();
        }
    
        private void LimitRotation()
        {
            float x = Mathf.Clamp(transform.eulerAngles.x, minRotation.x, maxRotation.x);
            float y = Mathf.Clamp(transform.eulerAngles.y, minRotation.y, maxRotation.y);
            float z = Mathf.Clamp(transform.eulerAngles.z, minRotation.z, maxRotation.z);
    
            transform.eulerAngles = new Vector3(x, y, z);
        }
    }