Ease float into set value

Here I have a script containing a function Accelerate() which when called, will increase a speed variable until the max speed is reached. Then, the object being moved will continue at the max speed.

I’m wondering if there is a cleaner way of implementing this sort of logic, as in my other more complex script it becomes a challenge when testing for potential player input.

All I’m really looking for is a simple method of easing a float into a set value.

Thanks for your help.

using System.Collections;
using UnityEngine;

public class SpeedTest : MonoBehaviour
{
    public GameObject movingObject;
    public float speed;
    public float maxSpeed;
    public float accelerationSpeed;
    public float topSpeed;

    //acceleration
    public IEnumerator Accelerate(Vector3 directionVector)
    {
        //accelerate until top speed is reached
        while (speed <= topSpeed)
        {
            speed += (accelerationSpeed * Time.deltaTime);
            movingObject.transform.Translate(directionVector * (speed * Time.deltaTime));
            yield return null;
        }

        //if top speed is reached, move at top speed
        while (speed >= maxSpeed)
        {
            movingObject.transform.Translate(directionVector * (speed * Time.deltaTime));
            yield return null;
        }
    }
}
if(accelerating) speed += accelerationSpeed * Time.deltaTime;
speed = Mathf.Clamp(speed, 0, maxSpeed);

The above, in Update… Simply change speed to 0 if you stop (or slow it down gradually). And have the bool set to true if you’re accelerating. The coroutine isn’t really necessary, imo, in this situation. You’re merely waiting a frame anyways, which is the same frequency as Update.

You could keep it and use similar code to what I wrote here, if you’d like, also. Whatever suits ya.

1 Like

Beautiful thank you! This should allow me to remove a lot of the coroutines in my scripts.

You’re most welcome. :slight_smile: CoRoutines are great at times, too. Just depends on the situation. Enjoy your project.