Ok, here’s a miniature function which could be very useful in many different situations, yet often people seem to struggle with it: interpolation of a number within a numeric range into another corresponding number within another arbitrary numeric range.
This sounds rather obscure, so let’s see a simple example.
Let’s say you have a container sprite that can have anywhere between 32 and 568 colorful balls attached to it. For whatever wicked reason you desperately need to express the current number of colorful balls in terms of the 0-to-16 numeric space.
Let’s assume that right at this very second you have 491 colorful balls on screen. You would do this:
trace (SimpleInterpolation (32, 568, 491, 0, 16));
… and voila, you would get a result of roughly 13.7. Basically this means that proportionally speaking 491 occupies the same spot in the 32-568 range as 13.7 does in the 0-16 range.
This is extremely useful for driving a set of values with another set of unrelated values (e.g. determining amount of objects by elapsed time), while always maintaining relative proportionality.
Have fun with the code, and remember who wuvs you.
// SimpleInterpolation function (C) edvardtoth.com // // baseRangeStart - start value of the base numeric range // baseRangeEnd - end value of the base numeric range // baseCurrentValue - an arbitrary value within the base range: this is the value that's going to be interpolated to a corresponding value within the target range // targetRangeStart - start value of the target numeric range // targetRangeEnd - end value of the target numeric range // // Basic example: SimpleInterpolation (0, 1, 0.6, 0, 100); // This will return 60 since in a proportional sense 0.6 in the 0-to-1 range is the same as 60 in the 0-to-100 range. function SimpleInterpolation (baseRangeStart:Number, baseRangeEnd:Number, baseCurrentValue:Number, targetRangeStart:Number, targetRangeEnd:Number):Number { var baseRangeFull:Number = baseRangeEnd - baseRangeStart; var baseFinalValue:Number; var targetCurrentValue:Number; if (baseRangeFull == 0) { baseFinalValue = 1; } else { baseFinalValue = (Math.min (Math.max ((baseCurrentValue - baseRangeStart) / baseRangeFull, 0.0), 1.0)); } targetCurrentValue = (targetRangeStart + ((targetRangeEnd - targetRangeStart) * baseFinalValue)); return targetCurrentValue; }
