## Tuesday, May 13, 2008

### ScaleTranslator: calculating corresponding scales

Suppose you have a slider with a scale of -34 to 299. And suppose you want that scale to correspond relatively to another scale, for instance a scale of 20 to 455, which represents, let's say, the x position of a sprite.

I've been breaking my head several times before on how to calcultate things like this. So I took pen and paper and found out that the formula to calculate the x position corresponding to the slider value looks like this:

b= ((a - A1) * (B2 -B1)/(A2 - A1)) + B1;

Where b (a number in the output range) corresponds with a (a number in the input range), and

A1 is the minimum Number of the input scale
A2 is the maximum Number of the input scale
B1 is the minimum Number of the output scale
B2 is the maximum Number of the output scale

I've put it into a class so you can use it like this:

var resultNumber: ScaleTranslator= new ScaleTranslator(A1, A2, B1, B2, a);
trace("resultNumber.getResult() =" + resultNumber.getResult());

Source and examples: scaleTranslator.zip

UPDATE 7.1.09
I updated the ScaleTranslator class (and decided to change the name to Mapper, easier to type) so you can call a static Mapper.map() function and get the output by only using one line:
var resultNumber: Number = Mapper.map(A1, A2, B1, B2, a);
You can find the Mapper class here