I have an AI Vehicle on a path and I want it to slow down from 40 to 15 smoothly using a box collider as a trigger. I tried doing some research and found that the math.lerp function can do what I need (I think). So I tried it but something isn’t quite working. I have no errors in my script but the speed is still dropping from 40 to 15 instantly. Please help. Thank you.
My current script:
The Time.deltaTime field is the percentage of how far across the other 2 parameters you want it to be. Time.deltaTime is approximately 0.02, which means it is nearly 40 or 15, depending on how you are passing it. You will want to throw this into a Coroutine, because as of right now, you are only calling Mathf.Lerp for 1 frame, and then stopping. You’re going to want to make the Time.deltaTime variable transition from 0 to 1 (1 = 100%). In your OnTriggerEnter, you can add a method call like this: StartCoroutine(SlowDown(0, 1));. Then, you can create a coroutine like this:
IENumerator ChangeSpeed(float start, float end) {
float t = start;
while(t < end) {
phantomCar.GetComponent<MoveOnPath>().speed = Mathf.Lerp(start, end, t);
t += Time.deltaTime;
yield return null;
}
}
By doing this, you’re evenly transitioning from start to end based on t, which is a percent. You can pass in different numbers as start and end to get different results (speed up, slow down).