I have written some code that creates a very nice uniform angular acceleration for an object moving around a circle. It effectively uses linear interpolation but ramps the interpolant such that the change is non-linear, hence the acceleration. The code is:
// Set the parameters to define the acceleration
float accelerationTime = 3f;
float startAngle = 0;
float endAngle = 180;
float currentAngle;
float startSpeed = 120;
float finalSpeed = 360;
float currentSpeed;
float radius = 3;
// Create the acceleration from 120 deg/s to 360 deg/s over a 180 degree angle within 3s
float t = 0;
accelFraction = 0;
Vector3 position;
while (accelFraction < 1f)
{
t += Time.deltaTime;
accelFraction = Mathf.Clamp(t / accelerationTime, 0, 1);
currentSpeed = Mathf.Lerp(startSpeed, finalSpeed, accelFraction);
float speedRatio = Mathf.Clamp(currentSpeed / finalSpeed, 0, 1);
currentAngle = Mathf.Lerp(startAngle, endAngle, speedRatio * accelFraction);
position = new Vector3(Mathf.Sin(currentAngle * Mathf.Deg2Rad), 0,
Mathf.Cos(currentAngle * Mathf.Deg2Rad)) * radius;
}
It allows me to accelerate from a start speed to an end speed, over a defined angular distance within a specific time. Great!
The problem is that I cannot figure out how to reverse this code to create the opposite effect, i.e. a deceleration. I have tried reversing the logic but it does not work, as counting downwards breaks the maths. Perhaps I am being obtuse but can anyone help here?
I would really like to keep my acceleration code the same; I suspect there is a simple tweak that I am missing. Any help is greatly appreciated!
1-accelfraction
when lerping for current speed. \$\endgroup\$