How to make flash games – Flash game dev 101

This is part one of a 2 part tutorial. For part 2 visit How to make Flash game – Part 2

In my last post we looked at the anatomy of a Flash game, the absolute bare minimum required to get something to happen, but where’s the fun in that! Today I want to build a (very simple) game which will give you an idea of some of the processes involved in designing and developing Flash games.

My original idea for this post was a complete “Flash game development 101″ which would outline the basic techniques used to build any Flash game, but the reality is that with so many different genres, from puzzle games to online driving games, platformers to multiplayer poker games, there simply isn’t one small set of techniques that covers all the bases.

In fact, to become a competent games developer you’ll need to learn a ton of different techniques, master at least the basics of Actionscript, plus learn a bunch of secondary techniques as well (like XML, PHP, databases, socket servers…)

So I’ve decided to be very specific in this tutorial. We’ll build a very simple but complete game. We’ll lay out specs for the game, build it one stage at a time and discuss each stage as we go, and at the end you’ll have a working game that you can extend and experiment with and even upload to your website for your visitors to play! Are you ready? Good, then let’s begin…

Flash Game Design

The first stage in development of any piece of software is design. If you sit down and start coding with no clear idea of what you’re trying to accomplish you’re setting yourself up for failure. With that in mind, let’s set out a design for our game.

Since this is a beginners tutorial, the game needs to be very simple (don’t worry – I’ll be going into more in-depth and interesting games in future posts!). With that in mind, games don’t get much simpler than the old “penny arcade” shooting galleries. So let’s build a very simple game, using the mouse to aim and shoot to hit some targets.

We’ll have 3 targets appear on the screen in random locations. The player’s goal will be to aim at the targets, clicking the mouse to shoot as fast as possible. The game will time how long it takes to hit all three targets, and that will be our score.

If that sounds incredibly simple, it’s because it is. It covers enough ground however to teach us quite a few aspects of game programming that you’ll use again and again in almost every other game you write. So let’s see what we’ll be learning:

  • FLA setup - We’ll need to draw, or import some graphics into Flash, set up a target movieclip, and set the game up to start, stop and show the score
  • Classes - We’ll create 2 classes for the game, one main class for the game, and also a target class for the target objects
  • User input – we’ll have to write code to take care of the mouse clicks and handle whether or not a target has been hit, we’ll also need at the very least a start button!
  • Animation - Very simple in this example, but we’ll need to show the targets getting knocked down, and the movement of a gun sight
  • Randomness - Used all the time in almost every single game, we’ll need to generate random positions for the targets
  • Timers - Another element that is used extensively in games, in this example we’ll be timing the shots to calculate a score

Sounds like a lot for such a simple little games doesn’t it? Well, we’d better get started then…

Setting up the FLA

The first thing we’ll need to do is create a new Flash project. Open Flash (you can download a free trial if you don’t already have it installed) and create a new Flash File (Actionscript 3.0)

Open the properties panel and set the framerate and size. I’m going to use 30FPS which is nice and fast and will give smooth animation, and 550×400px which is a good size since it should just fit on this blog! We also need to set a document class.  Since this game will be about shooting targets, let’s call our main class Targets – so type Targets into the document class field on the properties panel.  Then we need some graphics for our targets…

We have 2 options for the targets. We could draw them in Flash, or we could draw them in an image editor (like Photoshop) and import them as images. There are pros and cons to both approaches and I’ll discuss them in a future post, but for this game I’ve created the target images in Photoshop and saved them as PNG files. I’ve created one image for the full target, then a series of images with the target squashed and slightly darker. By showing these in sequence it should give the effect of the target falling backwards after being hit!  (You can use the targets I created by downloading the project file at the end of this tutorial, or you can draw your own!)


Sequence of target images

Creating the target movieclip

To import the target images click on the File menu Import > Import to Library… and select the PNG files.  You’ll then see them if you open the Library panel.  The library contains all the assets within a Flash file, like graphics, sounds, and movieclips, and you can create new instances of them by dragging them to the stage.

Find the target image in the library and drag it to the stage.  Now, with it selected hit the F8 key (or click the Insert menu and select New Symbol…)

This opens up the Create New Symbol dialog box.  We want to create movieclip so ensure that movieclip is selected, and let’s name it targetMC (for Target Movie Clip) and under linkage we’ll tick Export for Actionscript.  This allows us to assign a class to the movieclip, so in Class let’s give it a class name of Target.  Then click OK.

Later on we’ll write a class document called Target but for now let’s carry on setting up the movieclip itself.

On the timeline, click on frame 2 and hit F6 which inserts a new keyframe.  Then right-click on the target image and select Swap Bitmap… Choose the next image in the sequence (target_fall1) and click OK.  Now repeat that for the other frames in the sequence, and finally add a black keyframe (F5) to the end of the sequence.

Next, select the current layer and insert 2 more layers (either click the insert layer button, or use the right click menu).  We’re going to add a mask on the layer directly above our target (to remove any jagged edges) so select frame one of that layer, and using the elipse tool, with the SHIFT key held down to constrain proportions draw a circle on the screen.  Now select the circle and set its X and Y size using the properties panel to 66 pixels (1 pixel smaller than the PNG file) and position it directly above the target image. (you can use the align tool to make sure they are correctly positioned!)

The mask will need to be adjusted for each frame, so select frame 2 on the mask layer, insert a new keyframe as before by hitting F6 and using the Free Transform tool adjust the height of the circle to match the shape of the falling target.  Repeat this for all other frames…

Now right-click on the layer name for the mask layer and select Mask.  You should see the name of the targets layer indent, and the icon for both the target and mask layer turn blue (see the screenshot below).  You’ll notice that both layers are automatically locked, so you’ll need to click on the padlock icon if you want to edit them again.

Now on the top layer add a keyframe at the same position as the blank keyframe on the targets layer.  Single click on this frame and hit F9 to open the Actions panel.  In here type:

stop();

Then click on the first frame of this layer and do the same.  What this does it makes the target show frame 1 until we tell it to play, it will then display the frames in sequence (the “falling” animation) until it reaches the blank frame when again it will stop, giving the impression that it was hit and fell down!  Your timeline and movieclip should now look something like this: (If it doesn’t don’t worry – you can download the project files at the end of the tutorial!)


This is how your targetMC movieclip should look…

Writing the Actionscript

Save the FLA file, and from the File menu click New… and create a New Actionscript file.  We set our document class to Targets so now we’re going to write our Targets class.  To perform the most basic functions of our games we’ll need 4 methods (otherwise known as functions).  We’ll need a constructor method, called Targets(), which will be called when we run the game.  This will setup our game and call a second method which we’ll call addTargets().  This will generate random positions for our targets, and call the addTarget() method 3 times.  The addTarget() method will create a new target object and position it on screen, at the position of the parameters passed from the addTargets() method.  Finally we’ll need a method to handle when a target is clicked, we’ll call that clickTarget().

Notice that I’ve been quite descriptive with my method names.  We could have used any names we wanted (so long as we avoided reserved words – see yesterday’s post!) but by choosing descriptive names it makes it easy to see exactly what is happening, and that’s a really good habit to get into.  With only 4 methods it’s easy to remember what all the code in this example does, but on a big game with hundreds of methods you’ll easily forget if your naming conventions are illogical.

Here’s the code for the class.  Type it in (or download the project files) and save it as Targets.as and then I’ll explain each section in turn.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package {
    import flash.display.*;
    import flash.events.*;
   
    public class Targets extends MovieClip {
       
        private var targetList:Array;
        private var numTargets:int;
       
        public function Targets() {
           
            targetList = new Array();
            numTargets = 0;
            addTargets();
           
        }
       
        private function addTargets() {
           
            var thisX:int;
            var thisY:int;
            var xOffset:int = 33; // This is increased each iteration to keep targets separated...
            for(var i:int = 1; i<4; i++) {
                thisX = (Math.random()*100 + xOffset);
                thisY = (Math.random()*334 + 33);
                addTarget(thisX,thisY);
                xOffset += 190;
            }
           
        }
       
        private function addTarget(thisX:int, thisY:int) {
       
            var newTarget = new Target(thisX,thisY);
            addChild(newTarget);
            newTarget.addEventListener(MouseEvent.MOUSE_DOWN,clickTarget);
            targetList.push(newTarget);
            numTargets++;
       
        }
       
        private function clickTarget(evt:MouseEvent) {
           
            numTargets--;
            var obj = evt.target;          
            obj.removeEventListener(MouseEvent.MOUSE_DOWN,clickTarget);
            obj.play();
           
        }
       
    }
}

The framework of the class file you’ll recognise from yesterday’s tutorial, Anatomy of a Flash Game.  It starts by declaring a package, then there are 2 import statements – we’re importing the display package again (which includes the MovieClip class), and this time we’re also including the events package, because we’ll be making use of mouse events for when the user clicks on a target.

Then we have our class definition.  This names the class as Targets (the same name we set as the class definition in our FLA file!) and defines the class as an extension of MovieClip.

Next we have a couple of class variables.  First is an array, which is essentially a list, and we’ll use that to keep track of our target objects.  We also have a counter which I called numTargets which tells us how many targets we have.

Then comes our methods, let’s take a look at each of these in turn..

Our constructor method – Targets()

1
2
3
4
5
public function Targets() {
    targetList = new Array();
    numTargets = 0;
    addTargets();
}

Our constructor method must have the same name as our class, and must be declared as public (which means it can be called by other classes).  It will be called automatically when our game is run, and so we can use this method to set up our game.

For such a simple game we don’t need to do much.  First we create a new array (we declared an array variable already, but now we need to actually create an empty array), then we set the number of targets to zero (we’ll increase this number as we add them), and then we call the addTargets() method which will begin adding targets to the screen.

addTargets()

1
2
3
4
5
6
7
8
9
10
11
private function addTargets() {
    var thisX:int;
    var thisY:int;
    var xOffset:int = 33; // This is increased each iteration to keep   targets separated...
    for(var i:int = 1; i&lt;4; i++) {
        thisX = (Math.random()*100 + xOffset);
        thisY = (Math.random()*334 + 33);
        addTarget(thisX,thisY);
        xOffset += 190;
    }
}

addTargets starts by declaring 3 new variables.  These are method variables, which means they are only used within this method and are faster than class variables which need to be accessible to all the methods in a class.  thisX and thisY will be used for the X and Y coordinates of each target as we create it, and xOffset is half the width of the targets (which are 66 by 66 pixels.  You’ll see the reason for this in a moment!)

The next section of code is a for loop.  This loop will actually run all the code between the braces three times, to add 3 targets to the game with different positions on screen.  For each target a random horizontal and vertical position is generated.  They are prevented from overlapping by adding 190 to xOffset on each iteration.  This spaces them out evenly across the screen, and the 33 pixel offset ensures that they don’t ever go over the edge of the screen!

Each iteration of the loop calls the addTarget() function with the randomly generated x and y coordinates of the target to be  created…

addTarget()

1
2
3
4
5
6
7
private function addTarget(thisX:int, thisY:int) {
    var newTarget = new Target(thisX,thisY);
    addChild(newTarget);
    newTarget.addEventListener(MouseEvent.MOUSE_DOWN,clickTarget);
    targetList.push(newTarget);
    numTargets++;
}

The addTarget() method takes 2 parameters, the x and y coordinates of the new target.  The method takes these 2 parameters, defines a new variable, newTarget, and calls a method called Target().  If you’re wondering where the Target() method is, we’ve not written it yet – we’ll write that in the Target class in a minute (if you remember, we set up our targetMC movieclip with the class name Target in our FLA file!)

The next line, addChild(newTarget) adds our new target object to the display list (i.e. displays it on the screen).   Next we use a method from the events package which we imported at the top of our class file…

newTarget.addEventListener(MouseEvent.MOUSE_DOWN,clickTarget);

This creates an event listener and attaches it to our new target object.  What this does, as the name suggests, is to “listen” to this object, and when it is clicked by the mouse it will call the clickTarget() method.

Then we add our new target object to our array, targetList, and finally we increment our counter numTargets by one so we know how many targets we have!

OK so that was quite a lot for one method at this stage but don’t worry, we’re almost done…
private function clickTarget(evt:MouseEvent) {
numTargets–;
var obj = evt.target;
obj.removeEventListener(MouseEvent.MOUSE_DOWN,clickTarget);
obj.play();
}
[/cc]

The final method in the Targets class deals with what happens when a target gets clicked.  Remember the event listener we created? Well when that detects a click, it calls the clickTarget() method and passes an event object as a parameter.  That object allows the clickTarget() method to know what target was clicked, and take appropriate action – namely making the target fall down!

Firstly, a target has been hit so we decrement (reduce by one) our numTargets counter.  Then we declare an object variable to which we assign the value of the parameter object passed to the method (this allows us to now control the movieclip of the target which was just clicked!)

The next line removes the event listener from this object (the target has already been hit, so we no longer need to waste resources by listening for another click!) and finally we play() the target movieclip.  That advances the movieclip from where it was stopped on frame one, and it will show each frame in turn, at a rate of 30 frames per second, until it reaches the stop() command on the final blank frame.  That is what creates the animation of the target falling down!

Well done we’re almost finished!  Just one last thing to do, we need to also write the Target class, but luckily this is really simple with only one method.  Create another actionscript file, this time called Target.as and type the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
package {
    import flash.display.*;
    import flash.events.*;

    public class Target extends MovieClip {

        public function Target(targetX,targetY:Number) {
            // Set start position
            this.x = targetX;
            this.y = targetY;
        }              
    }
}

Only one method this time, a constructor again!  It takes 2 parameters and all it does is set the X and Y position of the target, see – I told you it was simple!

It might seem over the top to have Target in it’s own class, but believe me this is the best way to do it.  By breaking parts of your game down into small, easy to manage parts it becomes much easier to keep track of everything, and when we come to add extra functionality to the targets later on you’ll be glad we did it this way!

OK, time to save the file and we’re ready to test the game!  You can’t test from the Target class, so either select the FLA file, or the main class (Targets), ensure everything has been saved in the same folder with the right filenames (watch those capital letters!) and select Test Movie from the Control menu.  If all goes well you should see this…

Shoot each target as fast as you can!

Clicking each target should cause it to fall (to reset you’ll have to refresh your browser). If your program doesn’t work, or your get an error go back and double check your code, filenames, and the setup of your FLA file.

Now, give yourself a pat on the back because you’ve just created your first Flash game! But don’t celebrate too much, because it isn’t much of a game yet is it!

What we need to do now is turn this “framework” into a game which we can actually play and score.  We’ll add a gun sight to aim with, a start button for the user to click when they are ready to begin, and we’ll show how fast they were as their score at the end. Finally we’ll add a replay function so the player can have another go, and try to beat their score!

That will be part in 2 > How to make Flash game – Part 2

Share |

3 Responses

  1. Mike Says:

    Hello

    Great tutorial and game engine, thank you for helping beginners in action scripting as3. I have used the engine and made it into a small game with 4 scoring levels at the temporary link submitted. I have one question, I make other games and quizzes in as2 and use this code for the Submit Score button:

    on (release)
    {
    var gname = “SWF FILE NAME”;
    var gscore = _root.score;
    getURL(”index.php?act=Arcade&do=newscore”, “_self”, “POST”);
    }

    but I get errors in as3, I have tried different codes from the web that are used for as3 but they do not work. What code would you suggest or direct me to, that would submit that code.

    Thank You Mike

  2. admin Says:

    Hi Mike

    Thanks for your comment.

    getURL is deprectiated in AS3 so you need to use an alternative method. There’s a good discussion on how to approach this at Script Playground : getURL in Actionscript 3

    Hope that helps!

  3. Mike Says:

    I did get the game to score, thank you for the great game engine, it was really a lot of fun and good learning adventure expanding this into a 4 level scoring game, I used this code to get it to post a score:
    import flash.net.URLVariables;
    import flash.net.*
    import flash.net.URLRequestMethod;

    SubmitBtn.addEventListener(MouseEvent.CLICK, myButtonFunction);

    function myButtonFunction(event: MouseEvent):void{

    var myVariables:URLVariables = new URLVariables();
    myVariables.gname = “The Games Name”;
    myVariables.gscore = score var.text;
    trace(myVariables);
    var myURLRequest:URLRequest = new URLRequest(”index.php?act=Arcade&do=newscore”);
    myURLRequest.method = URLRequestMethod.POST;
    myURLRequest.data = myVariables;

    navigateToURL(myURLRequest, ‘_self’);

    }

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.