SHIP:Sail:towards

From Serious Documentation
Revision as of 07:37, 8 June 2015 by Admin (talk | contribs) (The doneWithin Parameter)
Jump to: navigation, search
Function Returns Introduced Description
towards Float/Integer v5.0.207 Adjusts a number by a percentage in a range towards another number.

See Also:

Prototypes

Float towards(Float percent, Float current, Float target, Float doneWithin);

Integer towards(Float percent, Integer current, Integer target, Integer doneWithin);

Parameters/Return Value

Parameter Data Type Description
percent Float Percent to move current towards target
current Float
Integer
Current value
target Float
Integer
Target ending value
doneWithin Float
Integer
When the result would be within this distance of the target, the target value is returned
Return Float
Integer
A new number "towards" the target

Detailed Description

The towards function moves a current numeric value towards a target value by a percentage.

The function is very useful in moving objects (e.g. gauge needles, sliders, boxes/images) in a fluid manner from their current positions to a target position. For example, when a slider needs to move from pixel position 55 to 85, rather than just assign the slider's position directly to 85 on a change, one can create a much more fluid movement using towards.

The structure of this would use a timer with a "current" variable within the object (such as a slider box):

   variable Integer target
   box
       timer oneshot=true value=1 period=1 autoreload=true enabled=false
           listener listeningto=timer.alarm condition=timer.alarm
               script
                   box.ol        = towards(0.33f, box.ol, target, 1);
                   timer.alarm   = false;
                   timer.enabled = (target != box.ol);
           listener target
                   timer.enabled = (target != box.ol);

The doneWithin Parameter

There is a floating point and an integer version of this function, and since rounding can play a role in the integer version as well as asymptotic behavior in the floating point version, the doneWithin parameter says that when the current is within that distance, it is adjusted to the target. For example, continuously moving 25% towards a target number using floating point values:

<code>

   Float f = 1.0f;
   (repeated) f = towards(0.25f, f, 5.0f, 0.1f);

Will, upon repetition of the formula, adjust f by 25% towards the target of 5.0 until is within 0.1 of 5.0, at which point 5.0 will be returned. Typically, the integer function will be supplied a 1 for the doneWithin parameter.

Examples

Example Result Notes
towards(0.25f,0,4,1); 1 25% from 0 to 4 is 1.
towards(0.25f,4,0,1); 3 25% from 4 to 0 is 3.
towards(0.25f,-4,4,1); -2 25% from -4 to +4 is 2.
towards(0.25f,3,4,1); 4 25% from 3 to 4 is 3.25, which is within 1 of 4, so 4 is returned.

References