Map function in Actionscript 3
I was reading an old blog post at: joelgillman.com and found an interesting function. The Map function ‘Re-maps a number from one range to another’ which basically means you can change the property of a value based on a different value. For example, in the code below I have used the mouseX property to move the sprite horizontally on the stage by moving the mouse across the stage.
var square:Sprite = new Sprite(); square.graphics.beginFill(0x000000); square.graphics.drawRect(0,0,50,50); square.graphics.endFill(); square.x = 0; square.y = stage.stageHeight/2 - square.height; addChild(square); addEventListener(Event.ENTER_FRAME, ef); function ef(e:Event):void { square.x = map(mouseX, 0, stage.stageWidth, 0, stage.stageWidth - square.width); } function map(v:Number, a:Number, b:Number, x:Number = 0, y:Number = 1):Number { return (v == a) ? x : (v - a) * (y - x) / (b - a) + x; }
In this example I have a movie clip with different key frames. I have used the mouseX property to cycle through the movie clip’s frames by moving the mouse horizontally across the stage.
addEventListener(Event.ENTER_FRAME, ef); function ef(e:Event):void { var frames:Number = map(mouseX, 0, stage.stageWidth, 1, square_mc.totalFrames); square_mc.gotoAndStop( Math.round(frames)); } function map(v:Number, a:Number, b:Number, x:Number = 0, y:Number = 1):Number { return (v == a) ? x : (v - a) * (y - x) / (b - a) + x; }
To use the map function you need to pass the following parameters:
map(value, low1, high1, low2, high2)
The value parameter is the value that is changing. I have used the mouseX in both examples above. The low1 and high1 parameters are the ranges the mouseX property can change. I have used from zero to the stage width in my examples. The low2 and high2 parameters are the properties values to be changed. In the first example, the sprite’s x property will move from zero to the stage width, and the second example the movie clips gotoAndStop() method cycles through the movie clips frames.