HyperBrid
HyperBrid

Reputation: 85

How to restrict Quaternion.RotateTowards() to clockwise-only rotation

I made a speedometer script for rotaing the needle in the speedometer
The Speedometer

public class Speedometer : MonoBehaviour
{
    public float zeroRate = 3f;
    [SerializeField] PlayerController vehicle;
    void Update()
    {
        if (vehicle.IsOnGround())
        {
            float zRot = ((vehicle.speed * 2.237f) / vehicle.maxSpeed) * 180;
            transform.rotation = Quaternion.Euler(0, 0, -zRot);
        }
        else
        {
            transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.identity, zeroRate * Time.deltaTime);
        }
    }
}

I'm facing the problem that the needle sometimes does a full 360 to rotate towards Quanternion.identity. I could use an if condition to check if the value goes beyond 180, subtract the twice the difference but the condition would check for this in every Update() call and would just clutter code with a 1-time-use-only if-condition. Is there a function that restricts the rotate in clockwise/anti-clockwise direction?

Upvotes: 0

Views: 339

Answers (1)

derHugo
derHugo

Reputation: 90714

Alternatively you could probably do something like store the last zRot value and over time reduce it and go

private float zRot;

void Update()
{
    if (vehicle.IsOnGround())
    {
        zRot = ((vehicle.speed * 2.237f) / vehicle.maxSpeed) * 180;
        transform.rotation = Quaternion.Euler(0, 0, -zRot);
    }
    else
    {
        if(zRot > 0)
        {
            zRot -= zeroRate * Time.deltaTime; 
            // clamp to 0
            zRot = Mathf.Max(0, zRot);
            transform.rotation = Quaternion.Euler(0, 0, -zRot);
        }
    }
}

Just that now zeroRate would be in °/second instead of radians/second in your version.

Upvotes: 1

Related Questions