BIT-101 [2003-2017]

Three useful methods


As usual, I was blown away by Robert Hodgin’s presentation at FiTC, and decided to get back into Processing again. I picked up the official Ben and Casey book at the conference book table and was reading it on the way back on the plane. Three methods described in the book blew me away with their simplicity: norm(), lerp(), and map().

norm(value, min, max) takes a value within a given range and converts it to a number between 0 and 1 (actually it can be outside that range if the original value is outside its range.

lerp(min, max, value) is linear interpolation. It takes a normalized value and a range and returns the actual value for the interpolated value in that range.

map(value, min1, max1, min2, max2) takes a value in a given range (min1, max1) and finds the corresonding value in the next range(min2, max2).

These are built-in functions in processing, but it didn’t take more than 3 minutes to implement these in ActionScript:

[as]package com.bit101.utils
{
public class NumberUtils
{
public static function normalize(value:Number, minimum:Number, maximum:Number):Number
{
return (value – minimum) / (maximum – minimum);
}

public static function interpolate(normValue:Number, minimum:Number, maximum:Number):Number
{
return minimum + (maximum – minimum) * normValue;
}

public static function map(value:Number, min1:Number, max1:Number, min2:Number, max2:Number):Number
{
return interpolate( normalize(value, min1, max1), min2, max2);
}
}
}[/as]

The immediate use I thought for these, especially mapping, is in making a slider or a scrollbar. You need to map the position of the slider button within its own min/max sliding area to the value that represents given the minimum and maximum values of the slider. And vice versa – if you assign it a value, you need to map that value to the position the handle should be at. I’ve done that lots of times, but it was always a bit messy. Just seeing the name of the function, “map” and its parameters, got me to see the problem in a new light. Now, getting the value of a slider becomes a one line operation:

[as]value = NumberUtils.map(handle.y, height – handle.height, 0, minimum, maximum);[/as]

« Previous Post
Next Post »