TUTORIAL: Building games in Flash 5
Part 1: Player movement and fire.
Author:
David Doull
Date: 23/02/01
Download source files: tut1.zip
Thanks: to Olorin and MadSci from flashkit for their assistance.
Aim: This is the first part of a series of tutorials that cover the techniques involved in building games in Flash 5. This tutorial covers controlling the movement of the player with the keyboard and firing weapons.
Assumed Knowledge: It is assumed that you have a basic understanding of Flash and Actionscript. You should understand variables, properties, if statements and the basics of the flash 5 'dot syntax'.
By the end: at the end of this tutorial you will have built a keyboard controlled spaceship that can fly and shoot around the screen, as shown below. You will also have learnt about 'Clip Events', 'keyboard control', 'array style referencing' and 'duplicating movie clips'.
OK, lets get going.
Open up Flash 5, set the background colour of the movie to black and on Layer one draw a spaceship. Select the spaceship, a choose Insert and Convert to Symbol (or F8) and make your spaceship a movie clip.
Select
this spaceship movie clip and in the Instance panel set the
movie clips name to spaceship.
If you don't want to draw a spaceship you can download this fla; tutorial1_part.fla, with this first step already done for you.
Step 2: Right, now lets get the spaceship moving!
The player will use the arrow keys to move the spaceship, up, down, left and right. So how do we do this?
We need to detect which key or keys are being pressed using Key.isDown and then adjust the spaceship x-position and y-postion accordingly.
Show me the code.
Lets have a look at how this is done. We are going to put almost all of the game code in clip events so if you don't know what clip events are then read on. (If you already know all about clip events then skip the next three paragraphs)
What are Clip Events?
Put simply, an event is 'something that happens', so a clip event is something that happens to a movie clip. More precisely it is an event that is associated with a movie clip. Two of the most useful movie clip events are 'load' and 'enterFrame' which occur when a movie clip is loaded and when it it enters a frame. The code looks like this
onClipEvent(load){
// code goes here}
Any code contained between the curly brackets will be run when the movie clip is loaded or first appears on the stage. The load event is useful in games for initialising variables and defining functions, anything you want to do once at the start of a game - like setting the score to zero. The 'enterFrame' event occurs every time the movie clip enters a new frame. So code you want to happen over and over again (such as detecting a collision) should be included in an enterFrame event.
Where do you type this clip event code? Select the movieclip and either right click and choose actions, or pick actions from the Window menu, the actions window will open and this is where you type your clipEvent code. This is similar to where you put code for buttons in Flash 4.
Setting the speed.
Right click on the spaceship movie clip and choose actions. In the actions window type
onClipEvent(load){
moveSpeed=10;
}
This sets a variable called moveSpeed to 10 when the spaceship is first loaded. This variable will control the number of pixels the player moves. So to make the player appear to move faster you would change this to a higher number.
Step 3: Keyboard movement
Next we are going to add the code for detecting the keyboard. We will let the
user control the spaceship using the arrow keys. Up arrow for up, left arrow
for left etc.
Under the onClipEvent(load) code type the following.
onClipEvent (enterFrame) {
if (Key.isDown(Key.RIGHT)) {
this._x+=moveSpeed;
} else if (Key.isDown(Key.LEFT)) {
this._x-=moveSpeed;
}
if (Key.isDown(Key.DOWN)) {
this._y+=moveSpeed;
} else if (Key.isDown(Key.UP)) {
this._y-=moveSpeed;
}
}
Now you should be able to use the arrow keys to move your spaceship smoothly around the screen. But what did those lines of code do?
The code is within an enterFrame clip event, which means that every time the movie clip enters a new frame the code is run. Effectively the code is run over and over again in a loop unless we remove or stop the movie clip.
But what key was pressed?
The first if statement checks if the key pressed is the
right arrow (referenced as Key.RIGHT). If the right arrow was pressed then the
code this._x+=moveSpeed; is run, otherwise it checks
if the left arrow was pressed and if it was pressed the code
this._x-=moveSpeed; is run.
The result of this code is to set a new x-position for the spaceship. If the right arrow is being pressed then this new x-position will be greater than the previous position, if the left arrow is being pressed then the new x-position will be less. How does it work?
this._x is a reference to the x-position of the associated movie clip.
In flash 4 you would have used a set Property command to set the x-position of a movie clip. In flash 5 you can do it by simply using _x. The word 'this' refers to the movie clip containing the script. So a line like this._x=10; would set the x-position of the associated movie clip to 10.
The += bit means 'add to the current value'. For example: this._x+=10; is exactly the same as this._x=this._x+10;
Simlialry the -= bit means 'subtract from the current value'. For example: this._x-=10; is exactly the same as this._x=this._x-10;
So why use += and -=? Because its less typing and its a popular shorthand that programmers use - hence its worth learning it so you can understand when other programmers use it.
Lastly the moveSpeed bit. Remember we set moveSpeed equal to a fixed value of 10 earlier. So if the left arrow was pressed the x-position would be set to the previous x-position -10 (ie: ten is subtracted from the previous x-position).
If the right arrow key is being pressed then the new x-position is the previous x-position plus 10.
so the code:
if (Key.isDown(Key.RIGHT)) {
this._x+=moveSpeed;
}
else if (Key.isDown(Key.LEFT)) {
this._x-=moveSpeed;
}
means: " if the right arrow key is being pressed down
then increase the x-position of the current movie clip (the spaceship) by the
value of MoveSpeed (which is 10),
Otherwise if the left arrow key is beign pressed down then decreasse the x-position
of the current movie clip (the spaceship) by the value of MoveSpeed (which is
10) "
Finally, the code:
if (Key.isDown(Key.DOWN)) {
this._y+=moveSpeed;
} else if (Key.isDown(Key.UP)) {
this._y-=moveSpeed;
}
does the same thing only it increases or decreases the y-position of the spaceship based on the UP or DOWN arrow keys.
If you want to skip all the above typing you can download the following fla: tutorial1_part1b.fla
Step 5: Now lets add in some weapon fire.
What we will do is create a movie clip that looks like spaceship laser fire. Whenever the Ctrl key is pressed we will duplicate this movieclip, set its location to the same location as the spaceship and then, within a loop, increase the movieclips x-position until it goes off the screen.
First up we need to draw some laser fire. On a new layer draw some laser fire, a couple of blue lines should do the job, select the laser graphic, convert to a MovieClip (F8) and set the instance name to laser.

You can download a source file with everything up to this step done for you : tutorial_part1c.fla
Now we need to and some new code to the spaceship clip
event code.
Select the spaceship movie clip and choose Window>Actions to open up the
Actionscript window. Add in the lines _root.laser._visible=false;
and laserCounter=1; so that the onClipEvent(load)
code is now:
onClipEvent(load){
moveSpeed=10;
_root.laser._visible=false;
laserCounter=1;
}
The first of these two new lines makes the laser invisible when the spaceship first loads. Why? because this will be our source laser clip. Whenever the user presses the Ctrl key we will duplicate this movie clip to create a new laser fire. Think of it as the mold from which we produce all the laser fire, this is the original movie clip and what gets fired across the screen every time Ctrl is pressed is a 'duplicate'.
The second line is just setting a counter variable equal to one. We'll use this variable next.
Step 6: Right, we've
mentioned that the laser will be fired when the Ctrl key is pressed, now let's
add in this code into the spaceship clipEvent. The following code goes directly
after the line
onClipEvent (enterFrame) { in the actions window
for the spaceship.
if (Key.isDown(Key.CONTROL)) {
laserCounter++;
_root.laser.duplicateMovieClip( "laser"+laserCounter, laserCounter );
_root["laser"+laserCounter]._visible=true;
}
This code is run when the Ctrl key is pressed. The code does three things. It adds one to the laserCounter variable, it duplicates the laser movie clip and makes the new, duplicated clip, visible.
The laserCounter++; bit adds one to the variable laserCounter. NB: ++ means 'increase by one', so the line is the same as laserCounter=laserCounter+1.
The second line duplicates the movie clip and gives this new duplicated clip the name 'laser' plus the value of the laser counter variable and sets the clips depth to the value of the laser count variable. So if _root.laser.count is equal to 4 then the new movie clip will have the name laser4 and the depth of 4.
The third line of code within the curly brackets makes
the new duplicated clip visible. You may not have seen this syntax before. It
uses array style referencing for objects and is especially useful if you want
to reference a dynamically created object name. It's kinda similar to how eval
was used back in Flash 4. For example: _root.laser._visible
can also be written _root["laser"]._visible
The normal dot syntax wont let you write _root."laser"+laserCounter._visible
- its incorrect. But you can do it using array notation, using square brackets!
We are almost at the end now, we just need to add some clip event code to the laser movie clip.
Select the laser movie clip, and choose Window > Actions to open the Actionscript window.
Type the following code:
onClipEvent (load) {
laserMoveSpeed=20;
this._y=_root.spaceship._y;
this._x=_root.spaceship._x+80;
}
Its some onClipEvent(load) code again. This time its associated with the laser movie clip so it will be run when the laser movieclip first appears on the stage. The code is also run whenever the laser movie clip is duplicated. When you duplicate a movieclip you duplicate the graphics, frames and all code associated with the movie clip. Each new duplicated movie clip has its own copy of the original movie clips code. And each duplicated movie clip runs its copy of the onClipEvent(load) code when its loaded or duplicated.
So what do those three lines do?
The first line just sets a new variable called laserMoveSpeed equal to 20. This
will be the number of pixels that the laser moves per frame. The second line
sets the y-position of the laser (or duplicated copy of the laser) to the same
y-position as the spaceship.
The third line sets the x-position of the laser (or duplicated copy of the laser)
to the same x-position as the spaceship plus 80. We add 80 because the x-position
is for the center of the spaceship and it looks funny to have the laser coming
from the center. Adding 80 makes it look like its coming from the front.
Now some enterFrame code:
onClipEvent (enterFrame) {
this._x+=laserMoveSpeed;
if (this._x>600){
this.removeMovieClip();
}
}
This code moves the laser movie clip (or duplicated copy of the laser) to the right of the screen. When the x-position gets greater than 600 it removes itself.
In a little more detail: the first line sets the x-position
of the laser movie clip (or duplicated copy of the laser) to the current x-position
plus laserMoveSpeed. As we set laserMoveSpeed to 20 this means that the x-position
increases by 20 every frame.
The next lines are an if statement, which simple removes the laser movie clip
if its x-position is greater than 600.
And that's it - if you followed carefully you should have a spaceship that you can move around the screen using the arrow keys and fire lasers with the Ctrl key. Hopefully you will also understand what the code is doing.
If you didn't get it working the final version can be downloaded here: tutorial1_part1d.fla
The next tutorial will build on this base to create a full game. We will add in scrolling backgrounds and some enemy spaceships to shoot at :)
Also thanks again to Olorin and MadSci for their assistance.
all the best David.
TUTORIAL: Building games in Flash 5
Part 2: Scrolling backgrounds.
Author: David Doull
Date: 10/04/01
Download source files: tut2.zip
Aim: This is the second part of a series of three tutorials that cover the techniques involved in building games in Flash 5. The first tutorial covers player movement and fire - if you haven't read it check it out: tutorial 1. This tutorial will cover scrolling backgrounds.
Assumed Knowledge: It is assumed that you have a basic understanding of Flash and Actionscript. You should understand variables, properties, if statements and the basics of the flash 5 'dot syntax'. It is assumed that you have read tutorial 1.
By the end: at the end of this tutorial you will have built a scrolling background for you game as shown below. You will also be introduced to the KeyUp clipEvent and parallax scrolling.
Click anywhere on the black to ensure that the flash
file has the 'focus'
Use the arrow keys to move, Ctrl to fire.
OK, let's get started.
The first thing we are going to do is to produce some ground that will scroll past as the spaceship flys over it.
Open up the flash file you produced at the end of tutorial 1 (or you can get it here).
Create a new layer (called ground) and draw some interesting ground - a few bumpy lines and some gradient fills should do the job. Make sure that the ground is the exact same size as the flash stage. Also make sure that ground will tile horizontally - so ensure that the ground starts and ends at the same height.
Select the ground, choose Insert and Convert to Symbol (or F8) and make your ground a movie clip.
Select this ground movie clip and in the Instance panel
set the movie clips name to ground (as shown
below).

If you don't want to draw the ground you can download this fla; tutorial2_parta.fla, with this step already done for you.
Step 2: Let's get the ground scrolling.
The ground will scroll to the left of the screen, which is achieved by gradually reducing the x-coordinate of the ground movie clip.
We actually need two copies of the ground movie clip placed next to each other to achieve a smooth scrolling effect. The second copy is sometimes referred to as a buffer. This ensures that the ground always covers the stage. There is a little flash file below that demonstrates this:
press the play button to see it in action.
When the first copy of the ground has moved completely off the left of the stage both copies of the ground are reset back to their start positions.
Duplicate the ground
As shown above, we will need a second copy of the ground
movieclip.
Which means we are going to duplicate the ground movie clip. So we will have
two copies of the ground movie clip next to each other.
Instead of moving both of these movie clips to create our scrolling, what we will do is put them inside another movie clip (which we will call mainGround) and then we can move this parent movie clip instead of the two ground movie clips. In other words the mainGround movie clip will contain the two copies of the ground and we will just move mainGround instead of moving the two grounds individually.
The first thing we need to is to put the ground movie clip inside another new movie clip.
Select
the ground movie clip and create a new movie
clip (Insert > Convert to Symbol or F8). Give it the name mainGround
and choose movie clip as the behaviour. Then in the instance panel set the instance
name of this new movie clip to mainGround
(as shown).
So what we now have is the ground movieclip inside of the mainGround movie clip. Why did we do that? Because we will now duplicate the ground movie clip within the mainGround movie clip. Then we will be able to move the two ground movie clips at once by just moving the parent mainGround movie clip. This will be less work for the flash player - as it only has to move one movie clip not two and hence will improve the speed of the scrolling. It seems like extra work for little pay off - but in building flash games the speed of the flash player is very important, so where-ever possible you should reduce the amount of code or movie clip manipulation that flash has to do.
We are now going to add in the clipEvent code for the mainGround
movie clip. Select the mainGround movie clip and choose Window > Actions
to open up the actions window then type the following.
Type the following code in the actions window.
onClipEvent (load) {
ground.duplicateMovieClip("ground2", 100);
ground2._x = ground._x+ground._width;
groundStartx = this._x;
groundSpeed=10;
}
This code is contained within a load ClipEvent, so it will be run when the mainGround is first loaded.
The second line of the code makes a duplicate copy of the
ground movie clip and gives it the name ground2
and a depth of 100.
The third line sets the x-position of ground2 to the x-position of the original
ground plus the width of the ground. This has the effect of locating ground2
exactly to the right of the first ground movie clip.
The fourth line creates a new variable called groundStartx which is equal to the x-position of the the mainGround movie clip. The purpose of this variable is to store the start location of the mainGround movie clip - we will use this variable later.
The fifth line groundSpeed=10; just sets up a new variable called groundSpeed with a fixed value of 10. This will be the number of pixels the ground moves per frame.
onClipEvent(enterFrame) code:
Directly below that type the following code:
onClipEvent (enterFrame) {
this._x-=groundSpeed;
if (this._x<= (groundStartx-ground._width)){
this._x=groundStartx-groundSpeed;
}
}
This is contained within an enterFrame onClipEvent so it will be run over and over again. Remember that the code within an enterFrame clipEvent is run everytime the movieclip enters a new frame. The mainGround movieclip has just one frame - but it is still constantly entering that one frame.
So what does it do?
The second line: this._x-=groundSpeed; reduces the
x-coordinate of the ground by the value of groundSpeed. As we set groundSpeed
to 10, then the code moves the mainGround
to the left by 10 pixels.
The third line checks to see if the mainGround has moved so far to the left that the first ground movie clip is completely off the stage, if this is true then the fourth line sets the x-coordintate of the mainGround such that it is positioned back where it started.
But what are all those variables
about?
this._x is the current x-coordinate of the mainGround.
ground._width is the width of the ground movie clip.
groundStartx is the variable we set up earlier. When the game starts the first
ground exactly fills the stage. So this variable stores the x-coordinate at
which the first ground fills the stage.
So groundStartx - ground._width is the start x-coordinate minus the width of the ground.
When the first ground is completely to the left of the stage its x-coordinate will be equal to its start x-coordinate minus its width. At this point the second ground will be exactly filling the stage.
When we reset the mainGround back to its start position on the stage we have to also subtract the groundSpeed because the mainGround still needs to be moving left by the amount specified in groundSpeed.
You can now test the scrolling ground. In the flash application the ground movement might look a little strange because in test mode the flash application allows you to see graphics that are off the stage - so test in a browser if you want to see only the stage.
OK, so now you have a nice scrolling ground below your
spaceship.
If you haven't got it working you can grab the source
file here.
Step 3: Even better scrolling
In most space games the ground doesn't just keep scrolling. What happens is that the player starts on the far left of the screen, when they get about a third of the way to the right of the screen they stop moving right and the ground starts scrolling. This is also what happens in a lot of platform games. So lets improve the ground scrolling to work like this.
Most of the code for this will be in the spaceship clip events. As the spaceship location will determine when the scrolling starts and stops.
When to start scrolling
Select the spaceship and open the actions window (Window > actions).
Within the onClipEvent(load) code, exactly under the line laserCounter=1; type the following:
scrollx=_root.mainGround.ground._width/3;
scrollStart=false;
The first line sets up a new variable, scrollx. This variable will be the x-coordinate at which the spaceship stops moving right and the ground starts scrolling. We've made it one third of the width of the ground.
The second line sets up another new variable called scrollStart. This variable will be set to true if the ground should be scrolling and false if the ground isn't scrolling.
OK, now what we want to happen is if the spaceship has
gone past scrollx then it will stop moving right and the ground will start scrolling.
So, we will need to change the code for handling the right arrow key.
The current code should be:
if (Key.isDown(Key.RIGHT)) {
this._x+=moveSpeed;
replace that with the following:
if (Key.isDown(Key.RIGHT)) {
if (this._x<scrollx){
this._x+=moveSpeed;
} else {
scrollStart=true;
}
What we have done is introduce an if statement. If this._x (the current x-coordinate of the spaceship) is less than scrollx then the spaceship x-coordinate is increased - hence it moves right. However if that isn't the case, then we set variable scrollStart to true and don't change the spaceship x-coordinate.
When to stop scrolling
Now, we to need add in a whole new bit of onClipEvent code, dealing with a whole new event.
Underneath all of the clipEvent code for the spaceship (after the last } ) type the following:
onClipEvent (keyUp) {
if (Key.getCode() == Key.RIGHT) {
scrollStart=false;
}
}
This code introduces a new clipEvent, namely keyUp. This event occurs whenever the player takes their finger off a key. Its useful here because what we want is for the ground to scroll while you are holding the right arrow key down, but to stop scrolling when you take your finger off the right arrow key.
The method Key.getCode() gives the last key that was released. So the if statement see's if the last key that was released was the right key and if that's true then it sets our variable scrollStart to false.
OK, not much more to do now. All we need is to add some code so that the ground actually stops scrolling when scrollStart is false.
Close the spaceship actions window and select the mainGround
movie clip.
Open up the actions window for mainGround (Window > Actions).
The current onClipEvent(enterFrame) code should be:
onClipEvent (enterFrame) {
this._x-=groundSpeed;
if (this._x<= (groundStartx-ground._width)){
this._x=groundStartx-groundSpeed;
}
}
Modify the code so it reads:
onClipEvent (enterFrame) {
if (_root.spaceship.scrollStart==true){
this._x-=groundSpeed;
if (this._x<= (groundStartx-ground._width)){
this._x=groundStartx-groundSpeed;
}
}
}
All that we have done is added in an if statement so that the code to move the mainGround only happens if the variable scrollStart is true.
A Tip: The line
if (_root.spaceship.scrollStart==true) could have been written as just
if (_root.spaceship.scrollStart)
if statements test a condition to see if its true. Generally they test if one
variable is greater than or less than or equal to some other variable. eg:
if (x>y). However when testing if something is true
you can simplify the code.
So if (x==true) can be written as if
(x). This is a really popular programming shortcut and is used quite
a lot.
Just remember that if (x) means if
x is true .
Finally, set the frame rate of your flash file to 25fps. (Choose Modify > Movie and type 25 in the frames per second box). A frame rate of 25fps should make the scrolling look quite smooth.
Test your movie, you should now find that the ground scrolls
when you reach a third of the way across the stage. If you want to skip all
the above typing you can download the following fla: tutorial2_partc.fla
Step 4 : Parallax scrolling
This example only has one scrolling background but you can improve the look of your game by adding in a second scrolling background. Your second background could be some stars or distant mountains. If you set the scrollSpeed for this background to a slower amount you will get an effect known as parallax scrolling - it gives a nice feeling of depth to the game.
Try adding in a second scrolling background yourself. You will follow the same steps and use the exact same code as you did for the ground. The only difference is that the graphic will be something different (eg: stars) and that the movie clip instance names will be different (eg: stars and mainStars). And the set the speed to a slower speed such as 4.
The code for you mainStars movie clip should be something like (assuming you have named your movie as stars)
onClipEvent (load) {
stars.duplicateMovieClip("stars2", 1000);
stars2._x = stars._x+stars._width;
starsStartx = this._x;
starsSpeed=4;
}
onClipEvent (enterFrame) {
if (_root.spaceship.scrollStart){
this._x-=starsSpeed;
if (this._x<= (starsStartx-stars._width)){
this._x=starsStartx-starsSpeed;
}
}
}
This source file demonstrates parallax scrolling with a stars background: tutorial2_partd.fla
TUTORIAL: Building games in Flash 5
Part 3: Enemies and collisions.
Author: David Doull
Date: 11/04/01
Download source files: tut3.zip
Aim: This is the third part of a series of three tutorials that cover the techniques involved in building games in Flash 5. The first two tutorials cover player movement, fire and scrolling backgrounds - if you haven't read them check them out: tutorial 1 and tutorial 2. This tutorial will cover enemies and collisions.
Assumed Knowledge: It is assumed that you have a basic understanding of Flash and Actionscript. You should understand variables, properties, if statements and the basics of the flash 5 'dot syntax'. It is assumed that you have read tutorial 1 and tutorial 2.
By the end: at the end of this tutorial you will have built a basic flash arcade game. A simple scrolling space shooting game which could be the basis for a scramble or defender clone. The tutorial also covers functions, for loops, random numbers, scoring and hitTest.
Click anywhere on the black to ensure that the flash
file has the 'focus'
Use the arrow keys to move, Ctrl to fire.
Step 1: Creating something to fire at!
First we are going to create some enemy spaceships to fire at.
On the main Timeline create a new layer and call it enemy.
On this new layer draw an enemy spaceship. Select the enemy spaceship, choose
Insert and Convert to Symbol (or F8) and make your enemy a movie clip.
Select this enemy movie clip and in the Instance panel
set the movie clips name to enemy1 (as shown
below).
If you don't want to draw the enemy spaceship you can download this fla; tutorial3_parta.fla, with this step already done for you.
The enemy spaceships:
Our game is going to follow a typical space shooting game
structure. The enemy spaceships are going to move across the stage from right
to left. The player will need to either dodge or shoot the enemies. If the player
shoots an enemy it will explode. If an enemy collides with the player the game
will be over.
We will use duplicateMovieCip to create multiple enemy ships.
Random start locations
Our enemies are going to start just to the right of the screen and move left. However if all the enemies started at the same location the game would be very easy and boring. We need to introduce a random element to the game. So all the enemy spaceships will start at the same x-position (to the right of the stage) but will each have a random y-position.
We will also make the enemy speed random, to add an extra challenge to the game.
Lets code
So we want to write code for setting up a random start position and speed for our enemy spaceships. To do this we are going to use something called a function. If you already know about functions you can skip the next three paragraphs.
What are Functions?
Functions let you group together lines of code. Often in game programming you want the same code to be run in different parts of your game. For example, you might want to increase the players score and play an animation if they collect a bonus. You might want the exact same thing to happen if they complete a level. You could write the code for collecting the bonus and then copy and paste it to the part of the game that handles completing a level. OR you could write a function to increase the score and play the animation and call the function whenever you wanted the score increase and animation to happen. The code for a function looks like this
function scoreBonus(){
// code goes here}
This is known as defining the function - it defines what the function is called and what code makes up the function. scoreBonus is the functions name. Any code contained between the curly brackets will be run when the function is called. 'Calling a function' means running a function and is done in your code simply by typing the function name. So the code scoreBonus(); will call the function resulting in the functions code being run.
NB: Defining the function doesn't actually run the functions code. The code is only run when the function is called.
A reset function
We are going to create a function to set up the start location and speed for the enemy spaceship.
Select the enemy movie clip and open the actions window (Window > actions). Type the following code:
onClipEvent (load) {
function reset(){
this._x=600;
this._y=random(200)+100;
enemySpeed=random(4)+1;
}
reset();
}
The code does two things, it defines the function called reset and then runs this function. The code is all within a load clip event so it will be run when the movie clip first loads.
The line function reset(){ defines the reset function. The next three lines are the reset functions code.
The line this._x=600; just sets the x-coordinate of the enemy spaceship to 600 (just to the right of the stage).
The line this._y=random(200)+100; sets the y-coordinate of the enemy to a random number between 99 and 299. random is a function that is built into flash - what it does is to create a random number between zero and 'one less than the number contained within the brackets'. eg: random(3) will create a random number between 0 and 2 (either 0, 1 or 2). We add 100 to the random number to ensure that the y-coordinate isn't at the very top of the stage.
enemySpeed=random(4)+1; sets a new variable called enemySpeed to a value random between 1 and 4. This will be the number of pixels that the enemy moves per frame.
Finally the line reset(); calls the function - which runs the code we defined above.
You might wonder why we bothered to create the reset function and then to just call the function right after we defined it? We could have just written the three lines of code and left out the function definition altogether. Well in the next step you will see that we also want to call the reset function elsewhere in our code.
Step 2: Getting the enemies moving
Ok, we have created our enemy movie clip and have set up its start position, now lets get it moving.
If you don't have it still open, open up the actions window for the enemy movie clip.
Underneath the code from the previous step type the following code for the enemies enterFrame clip event:
onClipEvent (enterFrame) {
if (_root.spaceship.scrollStart){
this._x-=enemySpeed+_root.mainGround.groundSpeed;
} else {
this._x-=enemySpeed;
}
if (this._x<-10) {
reset();
}
}
This code does two things; it moves the enemy across the stage by reducing its x-coordinate and it resets the enemy if it has moved off the left edge of the stage.
The first if statement checks to see if our variable scrollStart
is true?
If it is true then the enemy ships x-coordinate is decreased by enemySpeed+_root.mainGround.groundSpeed
otherwise it is decreased by just enemySpeed.
So if the ground isn't scrolling the enemy will be moved left by the random
number assigned to enemySpeed. If the ground
is scrolling the enemy's x-coordinate will be decreased by enemySpeed
plus the speed at which the ground is scrolling. We need to do this to ensure
the movement looks realistic. If the ground started scrolling and the enemy
just kept moving at the same speed it wouldn't look right (try it out if you
are not convinced).
The second if statement checks to see if the enemy movie
clip has moved off the left of the stage (i.e.: it's x-coordinate is less
than -10). If this is true then the reset
function is called. The reset function will
reposition the movie clip on the right of the stage and assign a new random
speed and y-coordinate.
If you test your flash file you should now have a enemy
spaceship moving across the stage and resetting itself after it moves off the
left side of the stage.
More enemies
But one enemy isn't going to be a very challenging game, so lets use duplicateMovieClip to add some more enemies. We will put the code to duplicate the enemy in a new layer on the main timeline.
Control Layer
Create
a new layer on the main timeline and call it control.
Click on the first frame of the control layer and open up the actions window
(either Window > Actions or right-click and pick actions).
Type the following code in the actions window.
numEnemy=3;
for (i=2; i<=numEnemy; i++){
enemy1.duplicateMovieClip( "enemy"+i, i+100 );
}
The first line creates a new variable called numEnemy and sets it to 3. This variable will be the number of enemies on the stage at any one point in time, if you want to make the game harder just try increasing this number.
The next three lines are a for loop. The loop duplicates the enemy1 movie clip.
What is a for loop?
For loops are used when you want to repeat some code a
set number of times. For loops use a counter, in our case its called i,
which is typically increased by one each time flash goes through the loop.
The line for (i=2; i<=numEnemy; i++){ is actually
doing quite a lot.
The i=2 bit sets a variable called i equal to 2 when
the loop starts. The i++ bit tells flash to increase
i by one everytime the loop is repeated and the i<=numEnemy
bit tells flash to keep looping while i is less than or equal to numEnemy. So
it will stop looping when i is greater than numEnemy.
The result of this is that two duplicates of enemy1 will be created, called enemy2 and enemy3. If you increase the value of numEnemy then the number of duplicate enemies will increase accordingly.
Now,
close the actions window and on the main time line add an extra frame to each
of the layers (as shown). Select the second frame of the control layer and insert
a keyframe (press F6). Open up the actions window for this frame (either Window
> Actions or right-click and pick actions) and type the following line:
stop();
This just stops the main timeline.
You might wonder how the game plays if the main timeline is stopped? Well, even though the main timeline is stopped the laser, spaceship and ground movieclips are still playing. The timelines of movieclips run independent of the main timeline, they will only stop if you specifically tell each one of them to stop.
You might also be wondering about why we used the control
layer.
We could have just put the code in any one of the other four layers. However
its much better practice to include all frame code in a separate layer. This
makes it much easier to debug your flash file and for other people to understand
your flash file. It also means that if you delete a layer to remove a graphic
you wont accidentally also remove some code. It has become a standard in the
flash programming community to call this layer control.
If you test your flash file now you should have three enemy spaceships flying across the screen.
If you don't want to type in all that code you can download the fla: tutorial3_partb.fla .
Step 3: Collision detection
We now have one key thing to do to turn this into a game. We need to add in collision detection.
We want to detect when a laser hits an enemy spaceship and consequently make the spaceship explode and disappear. Similarly we want to detect when an enemy spaceship collides with the players spaceship, at which point the game will end.
So how do we detect collisions in flash?
The spaceship, enemies and lasers are all movieclips. So we need a simple way to detect collisions between movieclips.
The answer is hitTest. Flash 5 introduced a method called hitTest which allows us to detect collisions between two movie clips and its really easy to use.
If you have two movieclips with instance names movie1 and movie2 then the code to detect a collision would be movie1.hitTest(movie2).
A few words about hitTest
There are actually two different ways you can use hitTest.
Usage 1: You can use it to detect the collision
(or overlap) between two movie clips using the syntax: movie1.hitTest(movie2)
This will be true if the bounding boxes of
the two movieclips are overlapping.
So what's a bounding
box? Think of it as an invisible rectangle drawn around the edge of a movie
clip. If you click on a movie clip in flash you will see the bounding box highlighted
(see right). hitTest detects when the bounding
boxes of two movie clips overlap, not when the graphics overlap.
The
image to the left shows the bounding boxes for the spaceship and the enemy.
The two bounding boxes are overlapping so if we used hitTest to check for a
collision it would be true even though the actual graphics don't overlap.
This isn't really a problem because the spaceship graphics mostly fill the bounding box and because the game moves so fast that players are unlikely to notice this lack of precision.
Usage 2: You can use it to detect a collision between a movie clip and a point. The syntax is movie1.hitTest(x, y, shapeFlag) where x and y are the co-ordinates of the point and shapeFlag is either true or false depending of whether you want to detect a collision between the movie clips graphic (true) or the movie clips bounding box (false). This usage of hitTest can give you a more precise collision detection but its not used much in games because we generally want to detect the collision between two movie clips not a point and a movie clip.
Using hitTest in our game
Let's write the code to detect the collision between the lasers and the enemies.
Open up the actions window for the laser (select the laser and choose Window > Actions).
The code for the lasers enterFrame onClipEvent should currently be:
onClipEvent (enterFrame) {
this._x+=laserMoveSpeed;
if (this._x>600){
this.removeMovieClip();
}
}
between the two curly end brackets type the following code:
for (i=1; i<=_root.numEnemy; i++){
if (this.hitTest( _root["enemy"+i])){
_root.score+=100;
_root["enemy"+i].gotoAndPlay( 2 );
}
}
This code checks to see if this laser movie clip is colliding with any of the enemy spaceships. It uses a for loop to check if this laser is colliding with each one of the enemy movie clips. If this is true it increases the score by 100 and tells the associated enemy to goto and play its frame 2.
The first line sets up a for loop. As explained before a for loop is a loop that repeats the code between its {}'s a set number of times. In this case the loop will repeat three times (as the value for _root.numEnemy is 3), and each time it repeats it will increase the variable i by one.
The second line is an if test. It checks to see if this movie clip (i.e.: the laser) is colliding with a movie clip specified by the code _root["enemy'+i] As explained back in tutorial one, this is array style referencing for a movie clip. So when i is equal to 1 then _root.["enemy'+i] will evaluate to _root.enemy1 when i is 2 it will evaluate to _root.enemy2 and so on.
If the hitTest is true then the next two lines are run.
These lines actually deal with some things we will set up in the next step.
The line _root.score+=100; increases a variable
called score by 100. We haven't set up this variable yet, we will do it in the
next step and you will see how easy it is to add a score to your game.
The other line _root["enemy"+i].gotoAndPlay(2);
tells the enemy that has collided with the laser, to goto its frame 2.
What we are going to do is put an explosion animation in the enemy movie clip
at frame 2.
The original laser - tidying things up
Now, before we leave the laser we are going to do one more
thing.
You may have noticed that the original laser movie clip (called laser) is never
removed. This is because the removeMovieClip method only applies to movie clips
that were created using duplicateMovieClip. As the original laser was drawn
by us it cant be removed using removeMovieClip and this is a good thing! If
we removed the original laser we wouldn't be able to duplicate new lasers from
the original.
So what happens to the original laser? We'll it cant be removed so it keeps moving to the right for ever. That seems a bit untidy, so we are going to add in an if statement which ensures that the original laser does nothing and only the duplicates fly across the screen and collide with enemies.
Exactly under the line onClipEvent (enterFrame) { add the
code:
if (this._name<>"laser"){
and after the second to last end curly bracket } put another end curly bracket
}.
This just adds in an if statement that makes the movie clip check which version
of the laser it is. If its the original version (the one with the name laser)
then the code to move, remove and check for collisions wont be run.
NB: you might not have seen <> before. It means NOT EQUAL TO, so our if statement will run the code if the lasers name is not equal to laser. In other words the code will be run if the laser is called something other than laser, such as laser2 or laser3.
You can get a source file with all the code and graphics up to this point here : tutorial3_partc.fla
Step 4: Scores and explosions
We are now going to add in a score display, some graphics to show the enemy exploding and some collision detection code which will detect if the players spaceship has hit an enemy spaceship.
Score Display
Close the actions window if it is still open.
On the main timeline create a new layer called score.
On this layer create a dynamic text box, you can put it anywhere on the screen.
Stretch the text box out so it is wide enough to display the score (as shown
below).

With
the text box selected click on the text options panel and set the drop down
list to dynamic text, the variable name to score,
uncheck the Selectable option and click the embed fonts button for numbers (as
shown on the right).
Now, still on the main timeline select the first frame
of the control frame and open up the actions window (Window > actions). Underneath
the existing code on this frame add the line
score=0;
This simply sets up the score variable and sets it to zero at the start of the
game.
Exploding enemies!
Now we want to add in an explosion animation for the enemy movieclip when its hit by a laser. Open the enemy movieclip in Edit mode. (Doubleclick the enemy1 movieclip on the stage or open the enemy movie clip from the library).
At the moment you should have one layer with one frame containing the enemy graphic. On that layer create four new keyframes and modify the graphic to depict the enemy exploding (as shown below). Select frame six of this layer and insert a blank keyframe (Insert > Blank key frame or F7).
Now
create a new layer (Insert > Layer) and call it control.
Select the first frame of this layer and open up the actions window for the
frame (Window > Actions). Type the following code:
stop();
Now insert a blank keyframe on frame 6 of this control
layer (Select frame 6 and then Insert > Blank key frame). Select the new
blank key frame on frame 6 and open up the actions window
for the frame (Window > Actions). Type the following code:
stop();
All we did was to cause the enemy movie clip to stop on
frame one and frame 6. But why?
We stop the enemy movie clip on frame one because we don't want the explosion
animation to play until the enemy is hit by a laser.
We have previously added the code to play the animation from frame 2 when the
laser collides with the enemy movie clip.
We stop the movie clip after the explosion on frame 6 because there are no graphics
on this frame. The movie clip still exists and will still keep moving across
the stage until it reaches the left hand side and is reset. However as there
are no graphics being displayed Flash wont detect collisions between the movie
clip and the spaceship or the lasers. Which makes sense, because we don't want
the enemy to collide with anything once its been blown up.
Step 5: Detecting a collision between the players spaceship and the enemy spaceships
So what happens when an enemy spaceship collides with the players spaceship?
At the moment nothing happens, it just passes through - which isn't very challenging. We are going to change things, so when the enemy collides with the player the game is over. We will add some code into the enemy1 movie clip to test if its colliding with the players spaceship and if this is true then main time line will move to a game over section.
So we have two things to do:
add the collision detection code into the enemy movie clip
and to create a game over section on the main time line.
Player / enemy collision detection
From the main time line select the enemy1 movie clip and open up the actions window (Window > actions).
At the end of the onClipEvent (enterFrame) code, just above the last end curly bracket } type the following code
if (this.hitTest( _root.spaceship ) ){
_root.gotoAndStop ( "gameOver" );
}
This is an if statement that checks if this movie clip (i.e.: the enemy) is colliding with the spaceship (in other words - if the bounding box of this movie clip is overlapping the bounding box of the player spaceship). If this is true, then the main timeline is instructed to goto and stop at the frame labelled gameOver.
Resetting after exploding
Before we close the actions window for the enemy1 movie clip we need to add an extra line to the reset function we created earlier.
We have set up the enemy movie clip to play an explosion
animation and stop on its empty frame 6 if it is hit by a laser. When it moves
off the left edge of the stage and is reset, it effectively becomes a new enemy
spaceship. Its the same movie clip, but for the player it seems like a new enemy
emerging from the right side of the stage. So we need to make sure that sure
that if it is was exploded that it is reset back to the first frame. All we
need to do is add the line
this.gotoAndStop(1);
as the last line of the reset function. This just ensures that when the enemy
is reset it is moved back to its frame 1. So the code for the reset function
becomes:
function reset(){
this._x=600;
this._y=random(200)+100;
enemySpeed=random(4)+1;
this.gotoAndStop(1);
}
Game Over
Great, now we want to set up a game over message, that is displayed if the players spaceship collides with an enemy.
You may want to do an animation sequence for the end of the game, but to keep this tutorial as simple as possible our end sequence will be one frame with the message Game Over and the final score.
Lets do it
Close
the actions window if its still open.
On the main timeline add an extra frame to the end of every layer, so you will
now have a 3 frame movie. Now, insert a blank keyframe (Insert > Blank key
frame) on frame 3 of the enemy, laser,
spaceship and control
layers (as shown on the right)
The main timeline stops on frame 2 while the game is playing. When the game is over it will move to frame 3. We inserted blank keyframes on the laser, spaceship and enemy layers because we don't want these movieclip still visible at the end of the game.
Select
the blank keyframe on frame 3 of the control
layer and in the frame panel give the frame
the label gameOver (as shown on the right).
Previously we set up the code for the main timeline to goto a frame labelled gameOver when a collision between the player and enemy is detected. We have now added in that label.
Still on the main timeline add in a new layer called game
over and insert a blank keyframe on the third frame of this new layer (select
frame 3 of the layer and Insert > Blank Keyframe).
Now, at this new keyframe add some text on the stage saying game over. It doesn't
matter what font or size or colour - just pick something you like. Move the
game over message to the middle of the stage.
OK, we now have the core game built. Give it a test!
The source file with all code and graphics up to here : tutorial3_partd.fla
Having tested the game you will probably have noticed two key things we need to improve.
1. We need a way to restart the game when its over.
2. At the moment you can fire lasers continuously which doesn't make the game
very challenging. What we want to do is limit the amount of laser fire on the
screen at any one time. This type of limited fire is common in arcade games
and means that the player has to think before they fire.
We will make both of these improvements in the next step
Step 6: A restart button and limited lasers
Restart button
So we need to add in a restart button at the end of the game, which will restart the game.
On
the main timeline add in another new layer and call it restart.
Insert a blank keyframe on the third frame of this new layer (Insert > Blank
keyframe). With this new keyframe selected draw a filled rectangle on the stage,
this will be the restart button. Add the text RESTART on top of this rectangle
(as shown on the right). Then select both the rectangle and the text and convert
to a button symbol (Insert > Convert to symbol , give it the name restart
and select behaviour button)
Now we are going to assign some code to the button. Select
the restart button and open the actions window (Window > Actions).
Type the following code:
on ( release ) {
gotoAndPlay (1);
}
This just tells flash to go back to the first frame of the main timeline when the button is released which will result in the game restarting.
Limited lasers
We want to limit the number of lasers that are on the stage at any one point it time. The code will limit the game to having a maximum of 4 lasers on the stage, but you can easily change this to any number you want.
We limit the lasers by keeping a count of how many lasers are on the stage and we wont duplicate a new laser if there are already 4 lasers on the stage. The concept is quite simple; when we create a new laser movieclip we will add one to a laser counter, when the laser moves off the stage we will reduce the laser counter by one, thus we always have a count of how many lasers are on the stage.
As the code for duplicating lasers is contained within the spaceship clipEvents we will need to modify that code.
Select the spaceship and open the actions window (Window
> Actions).
Some additions to the onClipEvent(load) code
First up we are going to add two new variable definitions to the onClipEvent(load) code. Type the following two lines exactly under the line scrollStart=false; and before the }
maxLasers=4; depthCounter=1;
The first line creates a variable called maxLasers and sets it equal to 4. This is the maximum number of lasers that can be on the stage. Just adjust this number if you want less or more lasers available. The second line creates a new variable called depthCounter. We use this to keep a track of what depth value to give our duplicated movie clips.
Changing the onClipEvent(enterFrame) code
We need to change the if statement that deals with duplicating
the laser. Replace the line if (Key.isDown(Key.CONTROL))
{
with the following code:
if (Key.isDown(Key.CONTROL) and (laserCounter<=maxLasers)) {
Now, the laser is only duplicated if the Control key has been pressed and the laserCounter is less than or equal to maxLasers.
We also need to make a few changes to ensure that the duplicated laser movie clips have the correct depth.
Replace the lines
_root.laser.duplicateMovieClip( "laser"+laserCounter, laserCounter
);
_root["laser"+laserCounter]._visible=true;
with the lines:
_root.laser.duplicateMovieClip( "laser"+depthCounter, depthCounter );
_root["laser"+depthCounter]._visible=true;
depthCounter++;
if (depthCounter>maxLasers){
depthCounter=1;
}
So why did we do that? We already had a variable called laserCounter which counts the number of lasers (it is increased every time a new laser is duplicated). We now also have a variable called depthCounter which keeps track of the what value to give for the depth of each duplicated laser. This variable depthCounter is increased by one when a new laser is duplicated, however when it reaches the value of maxLasers it is reset back to 1.
In flash when you duplicate a movie clip you have to give it a depth. If you give a movie clip the same depth value as another duplicated movie clip then the new movie clip will replace the old one. If we used the laserCounter for the depth we could find ourselves duplicating lasers with the same depth as lasers that are still on the stage. And so we use a separate depthCounter. The depthCounter just cycles in order through the values 1, 2, 3 and 4 while the laserCounter can be any value between 1 and 4 depending on how many lasers are on the stage.
There is now one last thing we need to do, add in the code to reduce the laserCounter by one when the laser moves of the stage.
So, close the Actions window, select the laser movie clip and open the actions window for the laser (Window > Actions).
Directly under the line if (this._x>600){ and above the this.removeMovieClip(); line add the following code.
_root.spaceship.laserCounter--;
This code reduces the laserCounter variable by one if the laser has moved off the stage (i.e.: its x-coordinate is >600).
Congratulations
Now test your game. You should find that the you can now restart the game when the game is over. And your lasers should be limited to four lasers on the stage at any one time.
CONGRATULATIONS you've completed the tutorial and now have built your own arcade game in Flash 5. The source file is available here: tutorial3_final.fla
The next step provides some suggestions how you can improve
and extend your game.
Extending and improving the game
These have been three quite long tutorials, but having completed them you should now have a good sense of how arcade/action style games can be built with flash 5.
While we have built a simple space flying game, many of the core elements of the game could be used in a variety of action games. Almost all action games involve player movement, enemy movement, collision detection and scoring, which were all implemented in this game.
Some suggestions on how the game could be improved:
To keep the tutorial from being too long, the game was kept as simple as possible. However there are quite a few improvements that could be made to the game.
1. Make the game harder by increasing the speed of the enemies or the number of enemies or limiting the laser fire.
2. If you noticed the game performing slowly or if movement was a little jerky, this would be because the graphics and stage in the game are quite large. Try reducing the size of the stage and game graphics. A smaller version of the game is available here tutorial3_final_small.fla
3. Try using bitmap graphics (eg: png format images) for the backgrounds. Flash is designed to work with vector graphics, but you can make fast and effective games using bitmap graphics provided you keep them small. See an example of using bitmap graphics for the backgrounds.
4. At the moment the player can move off the top, bottom and left of the stage which is a bit unusual. You can prevent this by including an extra test within you if statements for the player movement. eg: if (Key.isDown(Key.LEFT)) would become if (Key.isDown(Key.LEFT) and this._x>0)
5. Add in player lives so instead of the game ending when the player collides with an enemy, the player just loses a life. You will need to add in a lives variable and reduce this by one when the collision occurs. When lives is equal to zero the game will be over.
6. The game could do with some sound. For example: add an extra layer to the enemy movie clip. Put a blank keyframe on frame two of this layer and put an explosion sound at this frame.
7. The lasers currently keep on travelling even when they hit an enemy. You could change this by using the same code that is used to remove a laser when it goes off the stage to remove the laser when it hits an enemy.
Some further enhancements.
Here are some ideas for how you could really change and enhance the game.
1. Add in something to collect such as a bonus or people to be rescued (like in the old game Defender).
2. Change the movement and scrolling so that the background scrolls down the stage and the player moves up the stage. This could then be the basis for a space shooting game like the old games Galaga or Galaxian. If you change the background to look like a road you could have the basis for a top view driving game like the old game Spy Hunter.
Anyway, I hope you have you found these tutorials useful and I wish lots of success with your flash games.
Regards David Doull