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:
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.
return Math.random() * (max - min) + min;
}
Random int
and what if we don’t need decimals? Round’em!
return Math.round(Math.random() * (max - min) + min);
}
Random boolean
True or false? Flip a coin.
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.
return (Math.round(Math.random()) == 0):-1:1;
}
Random color
Really useful when drawing debug shapes on screen..
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)
return new Point(randInt(area.x, area.x + area.width), randInt(area.y, area.y + area.height));
}
