Rotating to the nearest "90" degree

Hey,
im making some kind of geometry dash game…
What im trying to do is to make player rotating when not grounded,
everything works fine instead of one thing…
When the player hits the ground it just rotates to 0 degree using Quaternion.identity,
and what im trying to do is to make player rotate to the nearest 90 degree smoothly…
My script:

    private void Update()
    {
        if (!isGrounded)
        {
            transform.Rotate(new Vector3(0, 0, -rotationSpeed) * Time.deltaTime);
        }
        else
        {
            transform.rotation = Quaternion.identity;
        }
    }

For any help Thanks! :wink:

OK, it looks like this is a 2D game, so you should represent your rotation angle as a simple float. The trick for turning smoothly is to maintain both a “target” rotation (what you’re transitioning to) and a current rotation. You can set the target rotation directly based on inputs or whatever, and then on every frame, you use Mathf.MoveTowardsAngle to move the current rotation towards that.

Perhaps something like this.

    public float rotationSpeed;    // how fast we spin while in the air
    public float recoverySpeed;    // how fast our actual rotation tracks the target

    float targetRotation;
    float currentRotation;
   
    void Update() {
        if (!isGrounded) {
            targetRotation -= rotationSpeed * Time.deltaTime;
        } else {
            targetRotation = Mathf.Round(targetRotation/90) * 90;
        }
       
        currentRotation = Mathf.MoveTowardsAngle(currentRotation, targetRotation, recoverySpeed * Time.deltaTime);
        transform.rotation = Quaternion.Euler(0, 0, currentRotation);
    }

Note that the way this is written, it’s fairly important that recoverySpeed be faster than rotationSpeed. We’re relying on that to make sure that while spinning in the air, the current rotation keeps up with the target. But then once grounded, we round the target to the nearest 90, and let the current rotation catch up to that over subsequent frames.

HTH,

  • Joe
1 Like

Thanks!
Everything works fine, but can you help me with one more thing…
sometimes it rotates to the left, and sometimes to the right.
I want it to rotate to the right everytime, any idea?

In that case, instead of Mathf.Round to find the nearest 90, you probably want to use either Mathf.Ceil or Mathf.Floor to find the previous/next 90 degrees.