Smooth rotation between 3 rotations

Hey everyone,

Imagine you control an airplane and when you press A on your keyboard, you want to rotate to the left with a max of 40 degrees. Same goes for pressing D, but then of course turn right. But, when you’re not pressing any of those keys, you want your plane to go to a 0 rotation again.

I’ve currently got a quick prototype working where I can rotate left and right to (around) a certain degree, but it’s not a great way to do it because it never hits a round number. My current prototype is as follows:

private void ApplyRotation(Rotate rotate)
     {
            var currentRotation = playerGameObject.transform.rotation.z;

            if (rotate == Rotate.Left && currentRotation <= 0.40f)
            {
                playerGameObject.transform.Rotate(Vector3.forward, Time.deltaTime * rotationSpeed);
            }

            if (rotate == Rotate.Right && currentRotation >= -0.40f)
            {
                playerGameObject.transform.Rotate(Vector3.back, Time.deltaTime * rotationSpeed);
            }

How can I improve this code, and, more importantly, how can I smoothly return to a 0 rotation when no key is pressed? Thank you :slight_smile:

1 Answer

1

Hey Serellyn,

I am assuming you just want the plane to turn around the z axis.

Let me walk this through with you.

Make sure your the pivot is in the middle.
You can have 3 different inputs, which will give you 4 different possibilities
Only A
Only D
A and D
neither
First you say how you want these different inputs to behave. I’d suggest something like:
Only A : Rotate in positive direction around the z axis (one turn speed, lerping speed, both).
Only D : Rotate in negative direction around the z axis (like only A).
A and D : Hold current rotation.
neither : Lerp to 0 rotation.

How do you want to receive user input (old or new input system)? I will do this with the old input system, as it’s rather code-based.
Also I don’t now how you want steering changes to behave, like easing from rotating from a negative into a positive direction, but I would continue like this:

You need:
The Plane Object as a parent for the plane visuals. Make sure that the parent object has a neutral rotation(0,0,0), if it doesn’t, it will mess things up. (For example don’t apply the script to a cylinder, that you have already rotated.)

The following is a bit janky, but it does the job, if you don’t play around with the given values too much.

public class PlaneRotation : MonoBehaviour
{
    /* Parameters you will need: */

    // Keep track of the current rotation
    float currentRotation;

    // The current velocity of the steer
    [SerializeField]
    private float currentVelocity = 0f;

    // The maxmimum velocity of the steer
    [Range(1.0f, 4.0f)]
    [SerializeField]
    private float maximumVelocity = 1f;

    // The acceleration until the maximum is reached
    [Range(0.1f, 4.0f)]
    [SerializeField]
    private float velocityAccelerationTime = 1f; // Seconds until max velocity is reached

    // The duration in which the speed can change
    [Range(1.0f, 4.0f)]
    [SerializeField]
    private float velocityChangeSpeed = 2f; // In seconds

    // Threshhold, when the velocity jumps to zero when stopping
    [Range(1.0f, 20.0f)]
    [SerializeField]
    private float velocityStopThreshhold = 0.25f;

    // The maximum rotation point
    [Range(1.0f, 179.0f)]
    [SerializeField]
    private float maximumRotation = 60f; // Degress of the maximum rotation (or not?)

    // The time, in which the plane smoothes back to idle rotation
    [Range(0.1f, 2.0f)]
    [SerializeField]
    private float smoothDuration = 1f; // Duration in seconds

    // Threshhold, when the velocity smoothes to zero when going idle
    [Range(0.1f, 12.0f)]
    [SerializeField]
    private float smoothOutThreshhold = 4f; // In degree

    // Threshhold, when the velocity jumps to zero when going idle
    [Range(1.0f, 4.0f)]
    [SerializeField]
    private float smoothStopThreshhold = 1f; // In degree

    // Whether to hardlock to maximum rotation or not (experimental)
    [SerializeField]
    private bool tryToLockToMaxRotations = false;


    private void FixedUpdate()
    {
        // Update current rotation
        currentRotation = transform.rotation.z;

        // Call this function in the fixed update method
        RotatePlane();
    }


    private void RotatePlane()
    {
        // Rotate the plane around the local z axis
        transform.Rotate(CalculateRotation());

        // Can help with going over the limit when not pressing a button but still rotating
        if (tryToLockToMaxRotations)
        {
            if (transform.rotation.z > maximumRotation / 100)
            {
                // Reset velocity
                currentVelocity = 0f;

                // Set to max rotation
                transform.rotation = Quaternion.Euler(0, 0, maximumRotation);
            }
            else if (transform.rotation.z < -maximumRotation / 100)
            {
                // Reset velocity
                currentVelocity = 0f;

                // Set to max rotation
                transform.rotation = Quaternion.Euler(0, 0, -maximumRotation);
            }
        }
    }


    private Vector3 CalculateRotation()
    {
        // When A and D are held down
        //
        if (Input.GetKey(KeyCode.A) && Input.GetKey(KeyCode.D))
        {
            // We want to not rotate here

            // When below the threshhold
            if (Mathf.Abs(currentVelocity) - velocityStopThreshhold / 180 < 0)
            {
                // Set velocity to zero
                currentVelocity = 0;
            }
            // Otherwise
            else if (currentVelocity != 0)
            {
                // Get gradually slower
                currentVelocity *= 0.9f - 0.9f * Time.fixedDeltaTime * (1 / velocityChangeSpeed);
            }
        }
        //
        // When A xor D is held down (xor means exclusive or, only if one is true, the bool is true)
        //
        else if (Input.GetKey(KeyCode.A) ^ Input.GetKey(KeyCode.D))
        {
            // Check whether A or D is held
            bool holdingA = Input.GetKey(KeyCode.A);

            // For the math
            int plusOrMinus = holdingA ? 1 : -1;

            // Rotate towards desired rotation

            // When at maximum rotation
            if (Mathf.Abs(currentRotation) * 180 > maximumRotation && currentRotation * plusOrMinus > 0)
            {
                // Set velocity to zero
                currentVelocity = 0;
            }
            // When one frame before maximum rotation
            else if (Mathf.Abs(currentRotation) * 180 + Time.fixedDeltaTime * (1 / velocityAccelerationTime) > maximumRotation && currentRotation * plusOrMinus > 0)
            {
                // Set velocity to the distance needed
                currentVelocity = plusOrMinus * (maximumRotation - Mathf.Abs(currentRotation) * 180);
            }
            // When next acceleration is above max speed
            else if (Mathf.Abs(currentVelocity) + Time.fixedDeltaTime * (1 / velocityAccelerationTime) > maximumVelocity)
            {
                // Limit velocity to the max
                currentVelocity = plusOrMinus * maximumVelocity;
            }
            // When below maximum velocity
            else if (Mathf.Abs(currentVelocity) < maximumVelocity)
            {
                // Accelerate
                currentVelocity += plusOrMinus * Time.fixedDeltaTime * (1 / velocityAccelerationTime);
            }
        }
        //
        // When neither A nor D are held down (and rotation is not zero)
        //
        else if (currentRotation != 0f)
        {
            // Get desired rotation direction
            bool rotateToPositiveDirection = currentRotation < 0f;

            // For the math
            int plusOrMinus = rotateToPositiveDirection ? 1 : -1;

            // Rotate towards desired rotation
            //
            // Jump to idle rotation, when below this threshhold
            if (Mathf.Abs(currentRotation) <= smoothStopThreshhold / 180)
            {
                // Reset speed
                currentVelocity = 0f;

                // Reset rotation
                transform.rotation = Quaternion.identity;
            }
            // Begin smoothing, when below this threshhold
            else if (Mathf.Abs(currentRotation) <= smoothOutThreshhold / 180)
            {
                // Decrease velocity
                if (smoothDuration > 0) currentVelocity *= 0.9f - 0.9f * Time.fixedDeltaTime * (1 / smoothDuration);
                else currentVelocity *= 0.9f - 0.9f * Time.fixedDeltaTime;
            }
            // When next acceleration is above max speed
            else if (Mathf.Abs(currentVelocity) + Time.fixedDeltaTime * (1 / velocityAccelerationTime) > maximumVelocity)
            {
                // Set velocity to max velocity
                currentVelocity = plusOrMinus * maximumVelocity;
            }
            // Accelerate, if velocity is below maximum
            else if (Mathf.Abs(currentVelocity) < maximumVelocity)
            {
                // Increase speed
                currentVelocity += plusOrMinus * Time.fixedDeltaTime * (1 / smoothDuration);
            }
        }
        //
        // In all other cases, reset velocity
        //
        else
        {
            currentVelocity = 0f;
        }

        // Return the desired value
        return new Vector3(transform.rotation.x, transform.rotation.y, currentVelocity);
    }
}

It just took me like 6 hours to complete this code, its 3:23 am rn. I have to sleep. I Apologize for errors, but it works. Try to fix some on your own!

Hope I could help!

Thank you for your help! Due to circumstances I've not been able to use your code yet. However, after reading it, it makes sense. When I get to it, I will let you know how it went. Thank you!

–

I think I realized an error I don't have time to fix rn, which is I am not using currentRotation = transform.rotation.(eulerAngles.)z;

–