Random Numbers in Flash

Random() is a very useful and interesting function that you use in a number of situations, mostly in games. In this tutorial I'm going to show you one use of random().

The basic code is:

random (value)

Now, if I were to type 3 in the place of "value", Flash would return 0, 1 or 2.
Why not 1,2 or 3? Because, as you've probably noticed, Flash starts from 0.


Now that we know the theory, let's move on to something more interesting.

Why not make a simple "game" using random()? Let's say, when you roll your curser over an object, it moves to another place:


[roll over the circle to make it change its x and y coordinates]





Here is how you:



iii. Draw a circle, select it and press F8. Convert the circle to a Button and call it "button".



iv. Press Ctrl + F3 to make the Properties window appear and then click once on the button you've created. If you've done that, under Button an empty white field should be visible. Let's type "circle" there. This is going to be the instance name of our button. What we do we need it for? You'll find out soon.

 

 


v. Now, select the circle, press F9 and copy (Ctrl + C) and paste (Ctrl + V) the following code into the ActionScript window that should appear before your eyes:

on(rollOver){
circle._x = random(250)
circle._y = random(250)
}


That's it. You've just created a simple a "game"!


How it works

on(rollOver){

We say what will evoke the actions that are between {} signs. In this case, this is the rolling over.

 

circle._x = random(250)
circle._y = random(250)

"circle" is, as we know, the instance name of our button. It is some kind of a name that we gave to this object and that we can use to refer to it in ActionScript . The dot and underscore is used in order to let Flash know that we actually want to refer to an object's property. There are many object properties such as:
 
Alpha
- circle._alpha = 30
Rotation - circle._rotation = 40 
X scale- circle._xscale = 25

... and more!



Well, I hope you are now able to use the random function.

Don't forget to see other cool tutorials!


Cheers!


Average: 3.9 (9 votes)