interpolation/Target/Float

From Second Life Wiki
Jump to navigation Jump to search

Summary

Function: float fTarget( float Now, float Target, float Min, float Max, float Vel );

Steps float 'Now' closer using increment float 'Vel' towards 'Target' while clamping between 'Min' and 'Max'. Useful for games, simulations and vehicles. For example keeping realtime track of linear and angular acceleration and velocity of a vehicle.
Returns a float

• float Now Current Value
• float Target Desired Goal
• float Min Clamp Minimum
• float Max Clamp Maximum
• float Vel Increment

Specification

float fTarget(float Now, float Target, float Min, float Max, float Vel) {
    if(llFabs(Target-Now) < Vel) {
        if(Target < Min) return Min;
        if(Target > Max) return Max;
        return Target;
    }
    if(Now < Target) Now += Vel; else Now -= Vel;
    if(Now < Min) Now = Min; else if(Now > Max) Now = Max;
    return Now;
}
// Released into public domain. By Nexii Malthus.

Examples

float Speed = 15.0;
float Desired = 45.0;

float Min = 0.0;
float Max = 40.0;

float Acceleration = 10.0;

Speed = fTarget(Speed, Desired, Min, Max, Acceleration); // Speed == 25.0 (Step closer to Desired)
Speed = fTarget(Speed, Desired, Min, Max, Acceleration); // Speed == 35.0 (Step closer to Desired)
Speed = fTarget(Speed, Desired, Min, Max, Acceleration); // Speed == 40.0 (Hit Max clamp)