Main Content

You are here:

Functions

Welcome back to Foundation Flash tutorials. Today I will be teaching you how to create a custom function and then call upon it. A function is some code that you can call upon by just saying the function name. For example, hitTest is a function that is prebuilt into Flash that checks whether or not one object is hitting another, and you can call upon it at any time. But say you wanted to create a custom function, that executed some code each time you called on it. Well, that's what we are going to do. The code will be:

duplicateMovieClip(_root.ball,"ball"+i,_root.getNextHighestDepth())
i++;

This is a duplicateMovieClip function, that you should remember from a previous tutorial. It just duplicates a Movie Clip called "ball", gives it an instance name of "ball" and then a variable i, which is increased, meaning that no two of its instance names are ever the same. A new part of this code, however, is the getNextHighestDepth function. What it basically does is get the next highest depth and returns it as a number, so we can write that in place of something like "98953+i" to get a unique depth. Now, we want to put this code in a function, that we can call upon, and the way we do that is:

function duplication(){
        duplicateMovieClip(_root.ball,"ball"+i,_root.getNextHighestDepth());
        i++;
}

How we write this is:

function functionname(){ code in here }

So, what we have done is create a new function called "duplication" and assigned it that code. Easy. Now, say we need to call upon that function. We would just type:

duplication();

Now, let's put this code into action. Open a new Flash document. in it, draw a ball, and convert it to a Movie Clip. call it "ball" and give it an instance name of "ball". Open up its action panel, and in it, type:

onClipEvent (load) {
        this._x = random(550);
        this._y = random(350);
}

This is for the duplication part, it means that whenever this Movie Clip (or a copy of this Movie Clip) loads, its x and y position will be random. Now, go to the first frame of your movie, and press F9, to open up its action panel. in it, type:

var i = 1;
function duplication(){
        duplicateMovieClip(_root.ball,"ball"+i,_root.getNextHighestDepth());
        i++;
}

So, we have our duplication function that we wrote earlier. Now to call it. Make a button and write "duplicate" On it. Open up its actions panel, and in it type:

on(press){
        duplication();
}

So, when the button is pressed, it calls upon our duplication function, and acts out the code in that function. If you test your movie, you should have something a little bit like this:

Well done, next time we will actually make a basic movement/enemy game, using the removeMovieClip function. Thank you for reading,

Leon.

Comments