By Zevan | January 6, 2009
Actionscript:
-
// this one-liner is good to know:
-
// Math.max(minValue, Math.min(maxValue, valueToClamp));
-
-
// wrapped in a function it looks like this:
-
const MIN:Number = 0;
-
const MAX:Number = 100;
-
-
function clamp(val:Number, min:Number = MIN, max:Number = MAX){
-
return Math.max(min, Math.min(max, val))
-
}
-
-
for (var i:int = 0; i<1000; i++){
-
var val:Number = Math.random()*1000 - 500;
-
// clamp the above random value between -100 and +100
-
trace(clamp(val, -100, 100));
-
}
Although I show a function implementation above, I use this technique inline a good deal. If there is some value that I need to clamp I'll often just "max min it":
Actionscript:
-
var val:Number = Math.random()*1000;
-
// clamp it - 0-100
-
trace(Math.max(0, Math.min(100, val));
Also posted in misc | Tagged actionscript, flash |
By Zevan | December 17, 2008
Actionscript:
-
trace((new Date()).getTime() + Math.random()*0xFFFFFF);
A hacky way to get a unique ID, although this isn't, perfect it works well enough. For a project that you really expect to get huge amounts of traffic... you might consider using php's uniqid() function and passing it into your swf. That said, the odds of two users getting the same two ID values are about as good as the odds of you winning the lottery twice in a row.
Here is a version wrapped in a function, with a prefix argument:
Actionscript:
-
trace(uniqid("z"));
-
-
function uniqid(prefix:String):String{
-
return prefix + (new Date()).getTime() + Math.random()*0xFFFFFF;
-
}
Also posted in misc, random | Tagged actionscript, flash |
By Zevan | November 14, 2008
Actionscript:
-
var s:Sprite = Sprite(addChild(new Sprite()));
A way to make a new sprite, add it to the display list and store a reference to it.
Figured this out on my own... but have since seen it around on a few flash blogs here and there... thought it deserved a post.
Also posted in instantiation | Tagged casting |