Let's make work a function: move a box randomly!

We have seen in our first tuto (Function made easy) what is a function and how it is implemented. We have given an example of how to add two numbers a and b.

What’s interesting in the function concept is that you can use it for very different operations.

In this tutorial we are going to see how it can be used to place an object randomly in the stage. 

 

Open a new Flash document and choose from the menu Insert/New Symbol; give it a name Box  and make it a Movie Clip type; click OK.

Then choose from the palette the Rectangle Tool and draw a square on the center stage.

Then click on the Scene 1 icon and drag from the library the Box Movie Clip to the stage (anywhere); in the Properties panel (menu Window/Properties), give it an Instance Name Box.

 

Now click on the timeline first frame and open the Actions panel from the top menu (Window/Actions); write what follows:

 

 

function placeBoxRandomly()

{

Box._x = random(400);

Box._y = random(400);

}

placeBoxRandomly();

 


Let me explain these few lines of code: the first line is, like explained in the first tuto (Function Made Easy), the function name called placeBoxRandomly (one word); notice that there is nothing between brackets because this function has no arguments.

 

Then we have the open curly bracket to announce the beginning of the definition of the function. Like said in the first tuto, I prefer to place the open curly bracket underneath the function name, because it will be easier to verify that for every open curly bracket, there must be a corresponding close one(all you have to do is look in the first column).

 

We have after that two lines that just say that the box x coordinate (horizontal position) and box y coordinate (vertical position) are random(400) , which means that it’s a random number between 0 and 400 pixels. You could use random(6) to play dice: you’ll get a random number between 0 and 6.

After that we have to close the definition of our function with a curly bracket.

The final line is the function call; every time you test your movie (with the menu Control/Test Movie command), Flash executes your program code; when it meets the name of your function, it executes the code between the two curly brackets.

 

One important thing: if you misspelled the name of your function for example by typing placeboxRandomly in your program (b instead of B), your program will not work; for Flash ActionScript language, the two names are not the same (stupid computer!); so be careful!

 

Instead of testing the movie with the menu command, try the Ctrl+Enter keypad shortcut: leave one finger on the Ctrl key and press the Enter key with another finger; every time you press the Enter key, the box moves on the stage randomly. That’s exactly what we wanted.

In the next tuto dedicated to the Flash function, we'll see how to use functions to make move a box with the arrow keys.