The web site for Flash ActionScript 3.0 game developers

 
         
   

Random Direction and Background

Hello there, I am a beginner at flash and have been trying to make a game.. Two things, the first is, that I want a Math.random that has the interval from -1 to 1, so that I can create a random direction for a ball. The other question is that I want to create a button that gives the background a random color. These are my problems, can you help me ?
Yours sincerly
Brian

If you are looking to create a random number from -1 to 1, which includes all stops in between, then you would need a range of 2, but lowered by 1 so it is -1 to 1 instead of 0 to 2. So, the statement would be var myRandomNumber:Number = Math.random()*2-1;
However, if your intention is to create a number that is -1 half the time and 1 half the time, then you can't simply round the number, as you would get -1, 0 and 1 at various times. So you would probably want: var myRandomDirection:int = (Math.random() < .5) ? -1 : 1;
The ? and : statement has three parts. The first checks to see if Math.random() is less than .5, which will happen 50% of the time. If so, then -1 is returned. Otherwise 1 is returned.
One way to create a random background color is to have a sprite that is a solid fill behind everything else. Then use the colorTransform to set its color. Like this:

var myColorTransform:ColorTransform = new ColorTransform();
myColorTransform.color = 0xFF0000;
myBackgroundMC.transform.colorTransform = myColorTransform;

To make it random, have the color value chosen at random from an array of possible colors.



Copyright Gary Rosenzweig