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;
}
}
}