Slowly slow down propeller and stop the values at 0f

Hello!
I have a engine script for airplanes. Now i want to make the prop slowly go from full speed to zero as you shut of the engine.

It does just like that, but the values keeps going negative instead of stoping att 0, the prop stops rotating as it should do att 0 value.
I have comment the line where the problem is.
I typing from my phone so i dont know if the code looks as it should do xD

Public float minRotationRPM = 30f;
Public float WantedRotationRPM =30f;
Public float ShutOfEngineRPM = 0f;

Public bool isShutOff = false;

Public Vector3 CalculateForce(float throttle)
{
float finalThrottle = Mathf.Clamp01(throttle)
if (!isShutOff)
{
finalThrottle = powerCurve.Evaluate(finalThrottle);
lastthrottleValue = finalThrottle;
minRotation = WantedRotationRPM; // want to slowly speed up again with the right code

}
else
{
lastThrottleValue -= Time.deltaTime * shutOffSpeed;
lastThrottleValue = Mathf.Clamp01(lastThrottleValue);
finalThrottle = powerCurve.Evaluate(lastThrottleValue);
minRotationRPM -= Time.deltaTime * shutOffSpeed; //This slowly slowing down the prop to 0 RPM as it should do and stop, but then the value dont stop at 0, it keeps counting down in negative values, and i need it to stop at 0 so i slowly can speed up the prop from 0 again to its fully RPM value again.

Just add a minRotationRPM = Mathf.Max(minRotationRPM, 0); at the end

The pattern I always use for these common move-towards problems is to have these three values:

CurrentRPM
DesiredRPM
const RPMChangePerSecond

Every frame in Update(), CurrentRPM does a Mathf.MoveTowards() the DesiredRPM by the amount of RPMChangePerSecond * Time.deltaTime.

That’s it. There’s really nothing simpler to code. You set the DesiredRPM you want, never think about it again, the CurrentRPM just takes care of it.

2 Likes

Thank you very much!