Basic random functions
- Posted by kajyr on November 28th, 2009
- Comment now »
Here are some really basic (but useful) functions that returns random stuff…
The really basic one, is built in the Flash api and it returns a Number between 0 and 1:
var n:Number = Math.random();
A number in a range
Sometime is more useful to have a random number in a different range, let’s say between 15 and 45, instead of 0 and 1.
public static function randNumber(max:Number = 1, min:Number = 0):Number {
return Math.random() * (max - min) + min;
}
return Math.random() * (max - min) + min;
}
Random int
and what if we don’t need decimals? Round’em!
public static function randInt(max:Number = 1, min:Number = 0):int {
return Math.round(Math.random() * (max - min) + min);
}
return Math.round(Math.random() * (max - min) + min);
}
Random boolean
True or false? Flip a coin.
public static function bool():Boolean {
return (Math.round(Math.random()) == 0);
}
return (Math.round(Math.random()) == 0);
}
Random sign
-1 or 1; Useful when you have to random select random rotation verse, for example, -1*45 or 1*45, rotates counterclockwise or clockwise.
public static function sign():Number {
return (Math.round(Math.random()) == 0):-1:1;
}
return (Math.round(Math.random()) == 0):-1:1;
}
Random color
Really useful when drawing debug shapes on screen..
public static function color():uint {
return Math.random() * 0xFFFFFF;
}
return Math.random() * 0xFFFFFF;
}
Random point
Inside an area. I like to use the flash.geom.Rectangle struct to describe an area, more than using 4 parameters (Flash api are quite inconsistent about this choice)
public static function point(area:Rectangle):Point {
return new Point(randInt(area.x, area.x + area.width), randInt(area.y, area.y + area.height));
}
return new Point(randInt(area.x, area.x + area.width), randInt(area.y, area.y + area.height));
}
Do you want to leave a comment?