How could randomly change the color of object in as3.
1
votes
2 Answers
4
votes
You can generate a random valid color like this: Math.round(Math.random()*0xFFFFFF)
.
For example, this draws 5 randomly colored squares:
for(var i:int = 0; i < 5; i++) {
var num:uint = Math.round(Math.random()*0xFFFFFF);
trace(num.toString(16));
var mc:Shape = addChild(new Shape()) as Shape;
mc.graphics.beginFill(num);
mc.graphics.drawRect(100*i,0,80,80);
}
Alternatively, if you need more control of the color ranges there is an working class here: QuasiUseful : AS3 Random Color Generator
1
votes
I agree with Shane. I would also add my prefered method of changing colors dynamically using flash.geom.colorTransform
.
This allows you to change colors for any shape, including irregular ones without having to know exact dimensions. You can use the following method, combined with Shane's random number generator code, to pwn this task.
import flash.geom.ColorTransform;
const INVALID_HEX_COLOR_VALUE:uint = 16777216; //Value that exceeds color range (over #FFFFFF)
function applyColorSchemeTo(obj:DisplayObject, otherColor:uint = INVALID_HEX_COLOR_VALUE):void {
if(obj != null){
var colorTransform:ColorTransform = obj.transform.colorTransform;
if(otherColor < INVALID_HEX_COLOR_VALUE)
{
colorTransform.color = otherColor;
obj.transform.colorTransform = colorTransform;
}
}
}