Those of you who read Flash and Flex Developer’s Magazine might have already read my Asteroids tutorial in the January edition.  If not, you can grab yourself a copy over at FFDmag.com

The tutorial shows you how to create a simple arcade game from scratch, based on the classic arcade hit Asteroids.  Rather than completely rehash the entire article here, what I wanted to do was back the article up with a little more info, show some of the setup in a more visual manner (with a short video) and then show how the game in the tutorial could be extended with extra features like audio, powerups and other game extensions.

In today’s post I’ll show you how to set up the Flash file, and go over how I designed and built the basic game.  Then I’ll follow up in a few days with a second post showing how to add extra functionality to the game, and get it to a level where it could be published online.  First of all, let’s take a look at the game… (note this is scaled down from full size of 800×600 px)

I’ve named it “Space Debris” but essentially it’s the same gameplay as the old Atari classic.  You move a small spaceship around the screen by rotating (cursors LEFT/RIGHT) thrusting (cursor UP) and firing bullets (X) in an attempt to destroy the asteroids.  Shoot a large asteroid and it becomes 2 smaller asteroids, they in turn become 2 yet smaller asteroids, and finally the smallest ones are removed when hit.  Clear the screen and you’ll have to face a larger, harder wave.

The player begins with 3 lives, they lose one if they crash into an asteroid, and the game is over when all lives are lost.  Pretty basic stuff right?

OK so the game will be written in a single class named Asteroids.as and we’ll also use a Flash file which will handle the intro/outro screens and hold our graphical assets etc.  In this video I’ll quickly show you how to set it up and then I’ll move on to actually coding the game, or simply click here to download all the source files.

Setting up the Asteroids game file

Writing the Asteroids game class

The following is taken from my article in Flash and Flex Developer’s Magazine January 2010 edition, reformatted slight for this blog but it is LONG!  I would highly recommend grabbing the FFDMag January edition and reading from that instead, which also includes full setup details for the Flash file!  Then just skip to the end of this post to grab the FLA and AS3 source files…

First create a new actionscript file and save it as Asteroids.as

Listing 1 (please download the AS files at the bottom of this page) shows the Asteroids class which extends MovieClip. It uses 4 imports, and has quite a number of class variables. Most of these are self explanatory such as lives or score. Some however need a little explanation.

We use 2 eponymous arrays to keep track of all the asteroids and bullets currently on screen, and we use a movieclip called gameField which will contain all the game objects (spaceship, asteroids, bullets).

The variable oldTime is used with our timer to calculate the new positions of each object on every frame, depending on their current speed and how long since the last frame.

The three booleans simply keep track of whether the ship is currently turning or thrusting, and then we have variables for all of the ship parameters, from how fast it rotates, to the maximum number of bullets it can fire.

Finally we declare 4 points, and another boolean. The points are the co-ordinates of the outer extremities of our ship and will be used when we write our collision detection function to see if the ship has crashed. The boolean simply tracks whether the game is currently playing (and the ship hasn’t already crashed!)

Beginning our game

You’ll notice that there is no constructor method. That is because we don’t want the game to start automatically, so instead we write a method called startGame() which we call frame 2 of our FLA file.

The startGame() method sets up our game by resetting variables such as level and score, creating new arrays to keep track of the asteroids and bullets, and creating our gameField movieclip which we move behind our control panel with the addChildIndex method.

We add 3 event listeners – one for ENTER_FRAME, which is our main game loop, and 2 for user input (KEY_DOWN and KEY_UP). We also call a method called addShip() which, as the name suggests, creates our ship object. We could also call nextLevel() from here to generate the first asteroid field, but instead we play the message movie clip, and add a listener which will call messageHandler() on each frame. The messageHandler() method in turn will call nextLevel() once the message “Get Ready…” has been shown on screen.

Main game loop

Asteroids in an action based game. Unlike a puzzle game or turn based game like Tic Tac Toe, or Sudoku, an action game has things happening all the time, on every frame, whether there is input from the user or not. To handle this we create a method called gameLoop() which is called every frame from the listener we declared above.

This gameLoop() method calculates the position of every object on screen, based on its velocity, and the time passed since the previous frame (see Time based animation post for more details). It does this by first getting the time in milliseconds since the game started and subtracting from that the time of the previous frame. This gives us the exact number of milliseconds since the last time the screen updated which is then passed to a number of methods to calculate the new positions of the ship, bullets and asteroids.

We also check for collisions (to see if an asteroid has been shot, or has crashed into the ship) and finally we update the text field for the score.

Game objects

We have 3 different types of game objects – our spaceship, the bullets it fires, and the asteroids. Each type of object has a method to create it, a method to move it (i.e. update its position on screen) and a method to remove it. Let’s look at each object type in turn.

Spaceship

Firstly the spaceship. This is what the user controls via keyboard inputs. It starts in the middle of the screen and there it remains until we give it some input. The addShip() method is very simple – it creates a new SpaceShip object, sets its position to the center of the screen, adds it as a child of the gameField object and sets the inGame variable to true.

The moveSpaceship() method is quite simple too, but involves just a little maths First it deals with the user input. If turnLeft or turnRight are true (set when the left/right cursor keys are pressed) then the rotation of the ship is either increased or decreased by the rotation speed.

If the thrust variable is set however there is a little more going on. We need to convert the thrust force into cartesian values for x and y. This is done with basic trigonometry If you think back to your trigonometry lessons from school you’ll remember that the x or y value can be found by using sine or cosine of the angle (rotation of the ship) multiplied by the hypotenuse (thrustAmt). We’re working in radians (rather than degrees) so we find the increase or decrease in x and y velocities like this:

1
2
shipDX += Math.sin(Math.PI*spaceship.rotation/180)*thrustAmt;
shipDY -= Math.cos(Math.PI*spaceship.rotation/180)*thrustAmt

Now that we know the velocities we can update the position of the ship by simply adding the new velocity values to the x and y co-ordinates of the ship. We also show frame 2 (the thrust frame) of the ship movie clip if thrusting, or frame 1 if not.

The last part of the moveSpaceship() method handles the edge of the screen. In Asteroids, the spaceship and asteroids “wrap” from one side of the screen to the other, and from top to bottom. To handle this we simply check to see if the ship’s position is outside of those boundaries, and if it is we wrap it to the opposite edge (with a little overlap of 20 pixels, roughly the width of the ship, which makes the transition look smooth!)

Removing the spaceship is actually handled by 2 methods – firstly we call explodeSpaceship() which sets inGame to false, moves the spaceship to the top of the gameField display list (to make sure it’s in front of the other graphics), and then plays the explode animation. We also take a life off at this point and update the lives field on the control panel.

An event listener is added which calls removeSpaceship() once the explode animation is completed. This removes the spaceship movie clip, then either calls addShip(), or if there are no lives remaining ends the game by playing the gameover frame in the messages clip.

Asteroids

At this point we have a spaceship flying around the screen, but that’s not much of a game on its own so lets add some asteroids! Again, we have methods to add, move, and remove, but we also have a method called nextLevel() which generates the entire asteroid field for the level.

Let’s begin with the addAsteroid() method. It accepts 3 parameters – asteroidType which is a string (big, medium or small) along with x and y co-ordinates. We declare a new MovieClip variable called newAsteroid, and depending on the asteroidType parameter we create a new big, medium or small asteroid object. We also give the new asteroid a random vertical and horizontal speed within certain limits (the smaller asteroids can move faster than the big ones!)

We then position the asteroid according to the x and y parameters, rotate it to a random angle and finally add it to both the asteroids array and the gameField movie clip.

Responsible for generating the asteroid field, and passing the parameters to addAsteroid is the nextLevel() method. It begins by incrementing the level variable (which we initially set to 0 in the startGame() method. We generate a number of asteroids, equal to the level number plus one so we open a for loop, and then create asteroids in random positions on the screen.

We don’t want asteroids to appear in the center (that’s where our ship is) or too close to the edges (otherwise they may instantly wrap which will cause a flicker) so we split the game field up into 4 quadrants. We randomly choose a quadrant, and then randomly generate a position within that quadrant to place the asteroid. That position, along with the size is passed to the addAsteroid() method to generate the asteroid field for the level.

Moving the asteroids is simpler than the ship since there is no user input to worry about, except that this time we loop through each asteroid in the asteroids array one by one. We again use the timeFrame parameter generated in gameLoop() but this time we simply move the asteroid based on its horizontal and vertical speed. We rotate it based on the difference between those 2 speeds (saves having to generate another random number, but keeps them all rotating differently) and we wrap at the edges just as we did with the spaceship.

While moving the asteroids is simpler than the spaceship, removing them is very slightly more complex. If it’s a small asteroid we can simply remove it, and increase the score. If it’s medium or large however we need to split it into 2 smaller asteroids. We do that by first checking the the type, and then calling addAsteroid() twice for the next size down. We also increase the score here, based on the size of asteroid hit, and finally we remove the asteroid both from the array and the game field.

At this point we also check the asteroids array to see if there are any remaining asteroids. If there are none then the level is over, and we play the messages clip from the “next level” frame, and add a listener which calls messageHandler() (and in turn the nextLevel() method) when the message finishes.

Bullets

Bullets are actually very simple since they don’t rotate, and they don’t wrap (we’ll remove them when they reach the edge of the screen). First we create a new bullet with the fireBullet() method which takes no parameters. It is called when the player hits the X key to shoot, and creates a new Bullet object. We calculate the new bullet’s velocity based on the current rotation of the ship in the same way we calculate the ship’s velocity. We then position the bullet just in front of the ship, add it to the gameField and the bullets array.

Moving the bullets is just like moving the asteroids in that we loop through the bullets array one by one. For each bullet we move it based on its velocity (multiplied by bulletSpeed) and we then check it against the edges of the gameField. Once the bullet goes beyond the edge of the screen we call removeBullet.

removeBullet() method accepts a single parameter, which is the index of the bullet in the bullets array. This method simply removes the bullet from the game field, and from the array.

Pulling it all together

OK so we now have a spaceship flying around the screen under the player’s control, we have asteroids floating through space, and we are able to shoot but there is one big element yet to code – the collision detection!

At the moment our spaceship is invincible, and our bullets pass right through the asteroids without making a dent. What we need is a final method added to our game loop which checks for collisions between the asteroids, and our ship and bullets.

So the checkColisions() method actually handles 2 different types of collision – asteroid/ship and asteroid/bullet. Let’s take a look at the ship collisions first.

First we check the inGame variable to ensure that the ship is still in play. If it is then we loop through the asteroids array and check each asteroid’s hit clip against each of the collision points on the ship using hitTestPoint with the shapeFlag parameter set to true (see collision detection box). The localToGlobal method is used to convert the collision points (which are relative to the ship) to global co-ordinates. If there is a match (i.e. if one of the collision points is within the boundary of an asteroid’s hit clip then there has been a crash and explodeSpaceship() is called.

For the bullet collisions we loop through the asteroids array, and for each asteroid we loop through the bullets array. Using hitTestPoint again, this time we simply check the bullet’s x and y co-ordinates against the asteroid’s hit clip. If there is a collision we call both removeAsteroid() and removeBullet(). We then break out of the inner for loop, using continue loopAsteroids; to prevent checking another bullet against the asteroid which has just been removed.

Finishing and running the game

The final methods, showScores(), restartGame(), keyIsDown() and keyIsUp() are self explanatory, and if you’ve followed the tutorial this far you should now have a simple but working game.

While this works as a great example for learning some of the fundamental principles of game development, and a few years ago it probably would have been enough to compete with many other Flash games on the web, these days players want something a little more refined.

{ End of magazine tutorial… }

Whew – I told you that was long!  OK, so rather than list all the actionscript here too I’ve put all the source files together in a zip which you can download here.

I really hope you enjoy tinkering with the game, and you learn a ton from it.  Please do give me some feedback, just leave a comment with any questions or suggestions and I will read them and resond.  Next week I’ll post a follow-up article which will extend the game, and audio and some other functionality, and basically turn it into a usable web game, so if you want to see specific features added do let me know!

In the meantime, have fun playing with it ;)

Download Flash Social Media Buttons
Download the Flash social media buttons components

Collision detection and collision reaction is a fundamental concept in game design. From puzzles to platformers, shooting games to driving games almost every genre will involve collision detection of some kind.

Collision detection in theory is quite simple – knowing when 2 game objects (or a single object and a point) are at the same location on screen, and acting accordingly. You might need to detect the edge of an object, such as a car bumping into another car, or 2 pool balls knocking together. Alternatively you might want to know when 2 objects actually overlap, such as a character collecting powerups, or an explosion causing damage.

Once you have detecting a collision, you then need the game to react accordingly – known as collision reaction. For our pool balls that would mean calculating the new speed and directions of the balls, for our powerup it might mean increasing the speed or firepower of player’s character, and for our explosion it might mean causing damage, or creating another explosion…

I’ll cover collision reactions in a future article, today I want to discuss a number of methods for detecting collisions in Flash and which method to use for what effect.

Collsion detections in Flash

There are several ways to detect in game collisions in Flash, and the best one to use will depend on the situation. First let’s take a look at 2 methods commonly used for just this purpose – hitTestObject() and hitTestPoint()

hitTestObject() as the name suggests will return true if 2 objects are overlapping, while hitTestPoint() will return true if an point is within an object. These 2 methods however are the source of much confusion and frustration with people leaning to develop games in Flash, and unless they are understood properly you’ll find that your results won’t always match your expectations.

hitTestObject()

hitTestObject() works on the bounding box of an object. This is fine if both objects being tested are roughly rectangular in shape, but for most objects it will return true when we don’t want it to.

As you can see in the above example, with the 2 square movie clips (on the left) the bounding boxes match the size and shape of the objects so in this instance hitTestObject would return true, which is what we would expect. Rotate them through 45 degrees however, and and you can see in the example on the right, even with the objects some distance apart the bounding boxes still intersect. In this example hitTestObject would again return true, even though our objects are not really touching!

As you can see, using hitTestObject for all of our collision detection would cause all sorts of problems, so let’s take a look at a simple alternative – hitTestPoint.

As the name suggests hitTestPoint checks a single point against an object. It also takes an extra parameter shapeFlag which allows us to check against the bounding box of the object (false) or the actual shape of an object (true).

This is much better, as it allows much finer control but there is a problem – we’re only checking a single point, not an entire object. There is however a simple solution to this – we set up an array of points around an objects edge, and we use hitTestPoint on each of them!

hitTestPoint()

This second example shows 2 square movieclips both 10 pixels square. We store the co-ordintaes of each corner (0,0 – 0,10 – 10,0 – 10,10) in an array, and loop the array using hitTestPoint on each point in turn.

hitTestPoint would return true for both objects with the shapeFlash parameter set to false, since the top right corner of object 1 (10,0) is within the bounding box and so is the top left corner of object 2 (0,0). However, if we use hitTestPoint with the shapeFlag set to true only object 2 would register as a hit!

HitTestPoint is really useful in all sorts of games, from checking whether a character’s feet are on the ground, to reacting when a car veers off the road surface. There is however a better solution which we could use in our pool ball example from above.

Since balls by definition are round, so long as we know their radius we can simply check that against their distance from either the center of another ball, or a surface such as the cushion on the edge of a pool table.

This is very easy to do, and only requires one calculation (rather than looping through an array of points). We simply use Point.distance(x,y) and compare it to the radius of the object – if it is smaller than the radius we know there has been a collision and we can act accordingly!

For every action…

We’ve really only scratched the surface of collision detections here, but you can now see how important they are. The real magic begins when we use that information (that a collision has occurred) to cause a reaction – from bouncing a ball off a wall, landing a spaceship, or exploding a bomb! But that is a lesson for another day…

In part one of this tutorial, How to make Flash games, we built a basic framework for a simple target shooting game in AS3. We set up a Flash FLA file for our game with a target movieclip, we wrote a main game class and a simple target class, and we randomly positioned 3 targets on the screen and allowed the user to “shoot” them by clicking with the mouse.

Now let’s take that framework and turn it into an actual game.  We’ll still keep things nice and simple, but by the end of this tutorial you’ll have a working game which you can then modify and extend as you wish.  So, here’s the functionality we’ll be adding:

  • Add a START GAME button so the player can choose when to begin, and a REPLAY button for multiple plays
  • Add a gun sight to aim with, rather than the mouse pointer
  • Add a simple score, which times the shots and gives the player something to compete against

Modifying the main class

We’ll begin by making a small change to the main game class, Targets.  In part one we wrote a method called Targets.  This is a constructor method, since it has the same name as the class, and so it runs automatically when we run the game.  This is no longer what we want, since we now want the game to begin only when the player clicks on a START GAME button, so let’s rename that method startGame().

We’ll also add a new method called endGame() and at the moment that will just have one statement – play().  When that method is called the game will move on from the current frame, and continue until it reaches a stop command which we’ll add shortly, along with a replay button!

Finally we need to edit the clickTarget() method.  We want the game to end when all of the targets have been hit, so add the following code right after the obj.play() line:

1
2
3
if(numTargets==0) {
    endGame();
}

numTargets is the number of targets on screen, each time one is hit numTargets is reduced by one, so when it equals zero we call the endGame() method and show the gameover screen!

Modifying the Flash game FLA file

So far we have only one frame in our game.  We now need 3 – one which shows a START GAME button, one which shows the targets and plays the actual game, and a final one which acts as a game over screen to show a PLAY AGAIN button, and later will also show the score.

Click on frame 1 in the timeline and press F6 twice, which adds 2 new keyframes.  Now on frame 1 we need a button.  You can either draw your own (press F8 to turn it into a button), drag one onto the stage from the components panel, or use the one provided in the project files.  Once it’s on stage go to the properties panel and give it the instance name of startGameBtn.

Now we’ll add the code to handle the button on the timeline, since it’s not really part of the game itself.  Click on frame 1 on the timeline, hit F9 to open the actions panel and type the following code:

1
2
3
4
5
6
stop();
startGameBtn.addEventListener(MouseEvent.MOUSE_DOWN, begin);
function begin(evt:MouseEvent) {
    startGameBtn.removeEventListener(MouseEvent.MOUSE_DOWN, begin);
    nextFrame();
}

The first command simply stops the timeline, since we don’t want to continue until the player clicks on the button. Then we set up an event listener (just like we did for clicking on the targets) and we define a function to handle the button click. The function simply removes the listener (good housekeeping!) and moves us on to the next frame where the game begins.

The game frame

Frame 2 is where the action will take place, but nothing will happen until we tell it to! Remember we changed the name of our constructor method? Well now we need to call it so we can start the game, so on this frame we add the code:

StartGame();

Game over frame

When all of the targets have been hit the game will play, so we need a stop() command on the game over frame.  We also need another button, just like on frame 1 but this time the button will take us back to the start.  Let’s also add a Game Over, or Congratulations type message to the stage!  Place another button on the stage, name it playAgainBtn and add this code to the timeline:

1
2
3
4
5
6
stop();
playAgainBtn.addEventListener(MouseEvent.MOUSE_DOWN, restart);
function restart(evt:MouseEvent) {
    playAgainBtn.removeEventListener(MouseEvent.MOUSE_DOWN, restart);
    gotoAndStop(1);
}

Now if we test our game we should have something like this:

(You might notice that the game over screen displays before the final target has fallen.  This is because the target animation takes several frames, so click on frame 2 in the timeline again and hit F5 a few times, that will give a delay of a few frames before the game over screen is shown!)

Gun sight – custom mouse pointers!

Clicking targets with a mouse is all well and good, but it would look a lot better if we were aiming with a gun sight rather than a mouse pointer!  Draw a gun sight on the stage (in frame 2), hit F8 and turn it into a MovieClip, and give it an instance name of sight (or you can just use the one I made in the project files!)

Now let’s edit the Targets class again to handle the sight.  First we’ll write a simple method which makes the sight object follow the mouse:

1
2
3
4
private function moveSight(evt:Event) {
    sight.x = stage.mouseX;
    sight.y = stage.mouseY;
}

Notice that the parameter is an Event, and again we’ll be using a listener to call this method.  This time however, rather than attaching the listener to a button we attach it to the stage, and the event we use is ENTER_FRAME which means that the moveSight() method will be called every single frame (30 times each second).  Here’s the code that we add to the StartGame() method:

stage.addEventListener(Event.ENTER_FRAME, moveSight);

We also need to hide the mouse pointer:

Mouse.hide();

We also need to include the Mouse class so we can use mouseX and mouseY so add this after the other imports at the top of the file:

import flash.ui.Mouse;

If you were to test the game at this point you’ll find that the sight goes behind the targets.  That’s because every time we add a new movieclip to the stage it gets added to the top of the display list, which makes it appear at the front.  Since the sight was in the game before we added the targets it’s at the back so we bring it to the front with this line, added after the addTargets() call in the StartGame() method:

this.setChildIndex(sight,this.numChildren-1);

Almost done.  Just a little tidying up to do.  Since we added an event listener to the StartGame() method, we should remove it in the endGame() method, and also show the mouse pointer again ready for the player clicking on the PLAY AGAIN button!  We also don’t want the sight on the game over screen, so let’s remove it.  Add this code to the endGame() method and then we ‘re ready to add the scoring:

1
2
3
stage.removeEventListener(Event.ENTER_FRAME, moveSight);
this.removeChild(sight);
Mouse.show();

Adding a simple score

We’re going to use a timer for the score, and we’ll be displaying the result in a text field so we need 2 more imports:

import flash.utils.Timer;
import flash.text.TextField;

Now in the FLA go to the game over frame and add a dynamic text field and call it scoreText.  You can also add some text saying that this is the final score, and we’ll add one more line of code on the timeline which will call a method to display the score:

getScore();

So to finish up the game let’s add the code needed to time the hits on the targets, and give the player a score they can try and beat each time they play!  Firstly we’ll need another class variable:

private var timer:Timer;

Then we need to add these 2 lines to the end of the startGame() method:

timer = new Timer(1);
timer.start();

This creates a new timer starting at 1, and sets the timer going.  It will count until it is stopped, so let’s add the following code to the endGame() method:

timer.stop();

Now all that’s left is to display the output of the timer on the game over screen, and for that we’ll write our final method:

1
2
3
private function getScore() {
    scoreText.text = String(timer.currentCount * timer.delay);
}

Well done, we’ve finished our little game and if you give it a test now you should see something like this:

How to make a Flash game – how to improve?

Well our little game is very basic, but in fact you’ve learned an awful lot by going through this tutorial.  You now know how to set up an FLA and a main class for a game, how to handle user input, control movieclips, handle simple animations, generate random events, deal with listeners and more…

Now I agree that this targets game on it’s own would get rather boring pretty quickly, but the best way to learn is by doing.  So why not take this example and experiment with it, extend it, put your own mark on it and create your own unique game?  (and if you do, post a link here in the comments so others can see your cool game!)

Here are a few examples of ideas for improving or extending the game, and more than likely I’ll return to one or two of these in a future article myself…

  • Format the score - Why not show the actual time in seconds and milli-seconds?  Or turn it into a countdown timer so the higher the score the better?
  • High score - Maybe you want a high score table so you can compete with your friends?
  • Accuracy - Perhaps you’d like the player to score better for being more accurate, and shooting nearer the middle of the targets?
  • More targets - What about generating new targets on screen as the old ones are hit?  You could keep generating new targets for 30 seconds and the score would be how many were hit in that time, or how accurately they were hit, or a combination of the two!
  • Moving targets - How about moving the targets around to make them more difficult to hit?
  • Bad targets - Taking that idea further you could have good and bad targets where the bad targets would make you lose points!
  • Ammunition - Maybe your gun can only hold so many bullets, and you’ll need to reload every few shots?
  • Different levels - Maybe this would be just one level, in a much bigger game.  Other levels might have targets moving across the screen, clay pigeons (skeets) to shoot, or any other type of shooting game – the only limit really is your imagination!

As you can see, once you learn how to write Flash games you really are only limited by your imagination.  Developing Flash games is a lot of fun, not to mention profitable if you get good at it and start attracting paying clients!

Over the coming weeks and months I’ll be adding more and more tutorials to this site, covering different aspects of game development, and showing you how to make Flash games of different types.  If you liked this tutorial and have any suggestions for future tutorials please leave a comment or send me an email, and if I like the idea I’ll use it!

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

OK so let’s start at the beginning.  What exactly do you need to start writing Flash games, and how do you begin to put one together?

Well these days you have several options.  You could develop Actionscript games using the Flex builder, or one of the opensource editors such as FlashDevelop, but for this tutorial I’m going to assume you’re using Flash.  You don’t need the latest version, but you do want to write Actionscript 3.0 code (more about that later) so anything from Flash CS3 upwards is fine.  If you don’t have access to Flash you can download a free 30 day trial of the latest version from the Adobe website.

Actionscript 2.0 or 3.0?

Actionscript is the programming language used to develop Flash games, and it’s come on leaps and bounds in recent years.  When I started developing Flash games there was no choice, it was just plain Actionscript (later known as Actionscript 1.0) until the release of Flash MX2004 when Actionscript 2.0 was released.  This was a huge leap forward and allowed much more performance and flexibility from the language.  It also intruduced a class based syntax, with inheritance like in languages such as C++ or Java.

The next big change came in 2006 with the release of Actionscript 3.0, which debuted with Flex 2.0 and the Flash 9 player.  AS3 was a huge change, and for the first time it became possible to write “serious” games for Flash.  A huge performance boost was very welcome, but existing Actionscript developers found themselves having to relearn the language.  The changes were so fundamental that it took many developers a long time to make the change, but luckily you won’t have that problem.  By learning AS3 right from the start you’ll be learning the “right” way to code, and you’ll be learning everything you need to make fantastic games…

Anatomy of a Flash Game

To create a game in Flash we need to create and work with 2 different types of file.  FLA files are Flash project files, they contain one or more timelines and can also contain vector and bitmapped graphics, audio, video and more, as well as Actionscript code.  AS files are Actionscript files and these only contain Actionscript code.  Once the game has been developed, we publish the game which generates an SWF file.  This is the actual game file which we upload and to a web server and display/play in the browser.  Let’s take a look at how we set up our FLA and AS files…

FLA, AS and SWF file icons

FLA, AS and SWF file icons

FLA file framework

Traditionally developers would include all the code for a game on the timeline in the FLA file.  Modern AS3 games however are developed with most of the code in external AS files.  This is a better approach, not only because it keeps all the code in one place which makes it easier to keep track of and edit, but also because those files can be reused in multiple projects.

The FLA file therefore, apart from containing any graphic or audio assets, buttons, video etc. is used to set up and “call” the external files needed for the game.  It is also used to set specific parameters, such as the framerate and size (resolution) of the game. Let’s get started, so open Flash and create a new Flash file (Actionscript 3.0)

When starting a new game project I first set the framerate, normally to 30 FPS (that means the screen refreshes 30 times per second) and set the resolution.  By default a Flash movie is 550 by 400 pixels, but many modern games are 600×500px or higher.  These settings are found by creating a new FLA file, clicking on the stage (the document part of the window) and opening the properties panel.

The next thing we do is set the main class for the game.  Basically this refers to the main actionscript file containing the code for the game.  Many developers call this file Main.as so the class would be Main (note the capital M!) but you can call it anything you like.  This is entered in the class field, again on the properties panel.

For a basic game that is all we need to do, so save the file and let’s move on to creating our main class file…

AS file (main class) framework

Our FLA file won’t do anything without some code to run so let’s create our first class.  Select New from the file menu, but this time rather than create a Flash file let’s select Actionscript file.

This time you won’t see a timeline, just a blank page with line numbers down the side.  This is where we type our Acionscript code, so let’s get started.  Let’s type the following code into the AS file, and then I’ll explain it line by line… (If you don’t want to type it you can download all the project files here)

1
2
3
4
5
6
7
8
9
10
11
12
package
{
    import flash.display.MovieClip;
   
    public class Main extends MovieClip
    {
        public function Main()
        {
            trace("This is my first Actionscript program!");
        }
    }
}

OK now I realise that might not make a lot of sense just yet, and all those curly braces might be a little confusing but bear with me.  Let me explain what each line does and why it’s there…

Package

Packages are groups of classes.  We group classes together to keep things organised, so for example all of the classes for a specific game project might be grouped as part of the same package.  You’ll notice that the word package is in blue.  This signifies that it’s a reserved word.  That means a special word which is used in Actionscript for a special purpose.  Later you’ll learn about variables, constants and functions which we can name whatever we like, but we must always remember not to use a reserved word as a constant or variable name (or the name of a class or function).  Flash turns reserved words blue to help prevent us making that mistake!

{ and } (curly braces)

If you’re new to programming these may seem a little odd, but in fact they are extremely useful.  They are used to show the start and end of sections of code.  In this example the very first { and the final } group the package, a second set group the class, and the third set are used to show the start and end of the function.  You’ll notice that these are nested.  That means that they are contained within other pairs, so for example the function is nested within the class.  This will make next sense in the next tutorial when you’ll see multile functions.

import flash.display.MovieClip;

This line is where the magic starts to happen.  Actionscript 3.0 allows us to create classes which extend existing classes.  So this little example program of ours is going to extend the MovieClip class.  That means our program will be able to do everything the MovieClip class can do, plus any specific functionality we give it!  This import command literally imports the MovieClip class into our new class and so we have access to all the functionality of MovieClip – cool huh!

Normally we’ll be importing a number of classes, but this example is so simple that MovieClip is all we need.  Note the capitalisation again, and the blue text!  Try typing movieclip without the capitals and you’ll see it’s black instead of blue.  Flash is case sensitive, so MovieClip is a reserved word, but movieclip is not.  Remember to get your capitals in the right place if you want things to work properly!

public class Main extends MovieClip

OK so now we’re defining our class.  Note that Main is in black, that’s because it’s not a reserved word, in fact I could have called it Billy or FlashGame or anything I liked, but I chose to call it Main and that’s what we entered in the class field on the FLA file.  This class will contain the code for our game.  Now remember I said that we were going to extend the functionality of the MovieClip class, well that’s exactly what we’re doing in this line of code.  The rest of the class definition will outline how we’re going to do that…

public function Main()

Functions (also known as methods) are like little helpers.  They are sections of code which perform specific functions (hence the name!) and we can make them do pretty much anything we want.  Our class can contain many methods, and they can call each other.  By that I mean that code in one method can ask another method for help.  This is one of the key concepts you’ll need to understand to start writing games, but don’t worry it’s really easier than it sounds once you see it in action!

Our class contains only one function – Main(). There are 2 things to note here.  Firstly you’ll notice that it has the same name as our class – Main.  This is no accident, it’s a special type of method called a constructor.  Constructor methods are called automatically when a program is run.  We could have called it something like StartGame() but we would then have had to add a line of code to our FLA file telling it to run the StartGame method… much easier to use a constructor!

The second thing you’ll notice is the parenthesis ().  These are empty at the moment, but are used to pass parameters to and from methods.  Parameters are bits of data needed by a function, and passed back and forth.  For example, if we write a method which adds two numbers together we might define a method called addNumbers(number1, number2) and so number1 and number2 would be the parameters.  When we want to add 2 numbers together we would do so by calling the method, and passing the numbers we want added like this, addNumbers(3, 4) and the method would take those 2 parameters, add them together, and return the answer of 7!

Even if a method is very simple and uses no parameters we still include the () after the name which defines it as a method.

trace("This is my first Actionscript program!");

Finally we get to some code which actually does something!  All the code we wrote up to now was really just getting set up, but this line actually generates some output!  In fact all it does is writes the words This is my first Actionscript program! in the Output window when you test the program, but at least it does something!

You’ll note that trace() is a function (you can tell from the parenthesis right!) and in this instance it has a single parameter, which is the text we want it to output.  We don’t need to know how the trace method works, only what it does and what type of parameters it takes (in this case a String – a line of text).

That is the power of methods, we can use them without needing to know how they work internally.  In the same way I can drive my car if I know how the steering wheel, gear stick and pedals work without needing to understand what goes on in the engine – see how powerful these method things can be! ;)

Finally you’ll see a semi-colon ; after the function.  This simply tells Flash that it’s the end of the directive.   We put a ; at the end of each line of code.  Now you might be wondering why there is a ; after the import line, and after the trace line but none of the others… if so, good question!

In fact those are the only 2 “proper” lines of code, the only 2 directives.  The other lines are all about defining the structure of the code, the package, the class or the functions…

Don’t worry if that seems a little arbitrary at this point, I promise that after you’ve started to write a few of your own simple programs you’ll get the hang of it pretty quickly!

Whew – OK now I realise that was a lot to take in, but trust me when I say that after seeing this a few times it will start to seem pretty obvious to you.  For now, let’s test our program!

Save the file as Main.as (again, we use the same name, with the capital M, as our class name) and then test our program by selecting Test Movie from the Control menu.  You should see the Output window open and display the line

 This is my first Actionscript program!

Congratulations, you just wrote your first Actionscript program and you’re well on the way to writing your first Flash game!

If you didn’t see that line, or if you got any errors go back and check each stage carefully.  Make sure your code is correct, your capital letters are in the right place, your class is set correctly in the FLA file and your files are names correctly and saved in the same folder.  You can also download the demo files below and check your code against them!

First steps to becoming a game developer

OK so I know our program didn’t do much, and it probably seems like an awful lot of work just to have a single line of text appear on screen, but believe me that you now have the knowledge needed to start creating games.  What we covered in this (rather long) tutorial is the foundation of every game you’ll ever write.  Every Flash game starts by creating a new Flash file, setting a class, and writing out a basic class structure just as we did here – it is truly the anatomy of a Flash game!

In my next post we’ll take what we learned today, and apply it to a proper game… until then I hope you found today’s lesson fun and useful, do leave a comment with your feedback or suggestions, and I’ll see you tomorrow for a proper game tutorial!

Download the tutorial files

Final note: We left out a vital step in creating a Flash game/application in this tutorial – we didn’t publish an SWF file!  As you learned earlier, SWFs are the actual files you upload to the web and play in your browser.  There’s a good reason for this though, out little “Hello world” example only used the trace function and that only works when testing the program in Flash – it’s relaly used as a helper when you’re coding, not for actually doing anything in published files.  In the next post we’ll use what we learned today and create a real game which we can publish and upload!