Over at Viral Flash Games, I’ve decided to give away the entire VFG1 games pack for free. These are older non-AS3 games, but there is still value in reskinning them, learning from them, re-using some of the assets or even porting them over to AS3.

I’m using the Pay With A Tweet system which means you just have to send a Tweet, or post a message to Facebook about the games and you’ll automatically get access to download all the source codes, FLA files and a licence to rebrand them, plus you’ll also get a preview PDF for the all new Viral Flash Games II with details of all the games and links to demos!

Here’s the link, go grab the games!

Earlier this week I announced that VFGII, the eagerly awaited sequal to Viral Flash Games, was coming soon. We I’m pleased to announce that the new games pack will launch this coming Wednesday, 5th December!

9 all-new games will be included, all coded in Actionscript 3, all with full source code! We’ve put together a PDF preview giving details of all the games which you can download HERE.

Watch this space for news of when we launch on Wednesday, or head over to ViralFlashGames.com and sign up to the email newsletter!

Over at Viral Flash Games we’re gearing up to launch an all new pack of 9 original AS3 games with full source code!  Following on from the hugely successful original VFG pack, the new games cover a wide spectrum or genres from racing, to shooting, puzzles, slots and more!  The pack even includes full source code to an iOS game, live on the app store, and built in Flash!

More details to follow when the games launch next week, but if you’re looking for AS3 games with full source code to learn from, or to reskin/rebrand then check out this blog post at viralflashgames.com

“>

In over 9 years of web game development I’d never used a third party framework until recently, preferring to code everything up from scratch. Both Flixel and FlashPunk had caught my eye though and for the past year or so I’d been meaning to try one or the other.

Well, a few months ago the opportunity presented itself. Hasbro hired us to develop a multi-world game to promote their new Kre-o range of toys and I decided it was the perfect project to test these frameworks with. Read the rest of this entry »

Browsing through the new releases on MochiMedia these days, you’d be forgiven for thinking that the most popular games genres are tower defence, “dress up” girl games and side scrolling, monster truck “stunt” driving games! Just because that’s what hundreds of newbie developers seem to be releasing doesn’t mean that’s what people want to play though!

Tower Defence I can understand, in fact some of the better tower defence games (such as Bloons Tower Defence or Desktop Tower Defence) are very popular at the moment, but there are 3 genres of browser games that are hugely popular, year after year. These types of games might not be groundbreaking, sexy or exciting, but they get hordes of players, and when well designed they tend to be guaranteed hits!

Last year MochiMedia ran a survey that showed the average casual gamer to be 43 years of age, and that 55% of players are female which goes some way to explain why arcade and strategy games don’t feature here. So, what are the 3 most popular genres…

Word Games

From the humble crossword to games like Word Reactor, words games are always popular, particularly with female players, and the older generations, word games attract large numbers of players and can be single or multi-player.

Since word games, in general, tend to be relatively simple to develop and with low overheads in terms of performance they are ideally suited to the Flash platform.

Card/Casino Games

Texas Hold’em on Facebook regularly attracts 15 million or more player per day! From Windows Solitaire to multi-player card games, this is an evergreen genre which always attracts players. The rules to many card and casino games are already well defined so you can spend less time tweaking and deciding on gameplay, and more time creating a polished experience.

Again since there is little in the way of graphical overhead these games are ideal for Flash, and work extremely well as browser based games.

Puzzle Games

Since Tetris is one of the best selling games of all time, it should come as no surprise that puzzle games are extremely popular online and attract huge numbers of players. Bejewelled, from PopCap games, has apparently been downloaded over 150 million times, and has sold over 35 million paid versions! Again, with a few exceptions, they tend not to be processor hungry and so are well suited to the Flash platform. While the term “Puzzle game” can encompass a wide range of game styles, generally they are 2 dimensional, and relatively simple both in terms of gameplay and development.

So, the next time you’re deciding on the next game you want to create, ask yourself what you want to achieve.  If you want to push the boundaries, and create a new, funky arcade game great – but realise that while a word or puzzle game might not be as interesting to develop, it could end up being way more successful!

This is a follow-up to the main tutorial from last week, How to write the arcade classic Asteroids in Flash, which originally appeared in the January edition of Flash and Flex Developer’s Magazine which can be found at FFDmag.com

In the tutorial we built a fully working, but rather basic version of Asteroids and today we’re going to add a couple of improvements.  I’ll leave features like power-ups and shields for a future post, but there is one gameplay tweak which is quit important.  In our original game we had no maximum speed on our spaceship, which meant that if the player held the thrust (UP) key down the ship would continue to accelerate ad infinitum.

That’s all well and good, but apart from looking glitchy one the ship starts travelling too far on screen each frame, if the ship is allowed to accelerate too much it could interfere with the collision detection, as it would effectively “jump” over an asteroid.  So today we’re going to fix that, and also add some simple audio so that it starts to feel like a real game.  Here’s an example of the updated game in action…

Setting a maximum speed

Our ship’s velocity is a vector, meaning it has both magnitude and direction.  That means we can’t simply check the current speed against a maximum speed and prevent further thrusting if it’s too high – that would prevent the player from turning, and thrusting away in a different direction.

There are several solutions to this, but since it’s such a simple game and we’re not interested in real-world simulations we’ll go with a nice simple one.  Effectively we’ll check both the X and Y velocity of the ship after the thrust key is hit, if the extra thrust would push either the X or Y velocity over the limit we won’t apply it!

This means our ship will have a higher maximum velocity if travelling diagonally on the screen than if it’s going straight up/down or left/right, but for our purposes that’s not much of an issue.

Coding the change

We’ll need one new class variable:

Then we need to make a change to the moveSpaceship() method.  Replace these lines:

1
2
3
4
5
if(thrust) {
shipDX += Math.sin(Math.PI*spaceship.rotation/180)*thrustAmt;
shipDY -= Math.cos(Math.PI*spaceship.rotation/180)*thrustAmt;
spaceship.gotoAndStop("thrust");
}

with this…

1
2
3
4
5
6
7
8
9
10
11
12
if(thrust) {
// Check if adding thrusting would exceed max speed, if not then thrust...
var tempDX:Number;
var tempDY:Number;
tempDX = shipDX;
tempDY = shipDY;
tempDX += Math.sin(Math.PI*spaceship.rotation/180)*thrustAmt;
tempDY -= Math.cos(Math.PI*spaceship.rotation/180)*thrustAmt;
if(tempDX < shipMaxSpeed) {
shipDX = tempDX;
}
if(tempDY < shipMaxSpeed) {      shipDY = tempDY;    }   spaceship.gotoAndStop("thrust"); }

As you can see, we’ve calculated the new thrust values for a pair of temporary variables, then we compare the new velocities based on these values, and only if they are below the maximums do we apply them to the actual ship velocities shipDX and shipDY.

Adding audio

No game is complete without sound effects, so take a look at a couple of ways of adding them to a game. I won’t go into detail here about using sound channels and transforms to allow for mute controls etc, that can be another post another time, for now let’s just get some simple sound effects into the game. First we’ll need some sounds. Flash will support Wav or MP3 format audio and there are loads of sites online where you can download free (or cheap) sound effects in those formats. If necessary you can trim or edit them using something like Audacity and then you want to import them into our FLA file. Go File > Import to Library and select all of the sounds you want to import. I’ve imported 4, one for the ship exploding, one for the ship firing, one for hitting an asteroid, and one for end of level/game.

The simplest way to add a sound is on the timeline.  Open up the ship movieclip and add a new level called audio.  Add a new keyframe (F6) on frame 3 (the same frame that the explosion animation starts) and on the properties panel, click on the Sound dropdown and select the sound you want to play when the ship explodes.  You’ll notice a waveform for the sound shown on the timeline, as shown below.

Adding sound to the timeline

Adding sound to the timeline

You can do the same thing in the messages movieclip to add the end of level, and end of game audio.

Now the asteroid getting hit, and the ship firing can’t be done in this way since they don’t have animations, but that’s good because it gives us a good reason for using Actionscript to play the audio.  Controlling sound with Actionscript is much more powerful than using the timeline as it gives loads of extra control, and allows us to do things dynamically (it’s also how we would add a mute or volume control to the game!)

First of all we need to right-click on each of the audio assets we intend to control in the library, check the “Export for Actionscript” setting and give them an appropriate class name:

Check Export for Actionscript and give it a class name

Check "Export for Actionscript" and give it a class name

To use simple sound we need to add one new import to our AS file:

1
import flash.media.Sound;

Then we need to declare a class variable for each sound we want to use:

1
2
private var thisExplode:Explode = new Explode();
private var thisShot:Shot = new Shot();

The type is whatever class name we gave that sound when we set the linkage (and is case sensitive!)

Then we simply use Sound.play() to play those sounds at the correct moment. So add this line to the fireBullet() method right after adding the bullet to the bullets array:

1
thisShot.play();

And add this line to the removeAsteroids() method, right after splicing the asteroids array:

1
thisExplode.play();

That’s all there is to it.  We now have basic, but fully working audio in our game!

As usual, comments or questions are very welcome.  I’ll come back to this again in a week or so and we’ll add some other gameplay features such as powerups!

(If you want to see the original Asteroids tutorial, and download the source files click here)

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…

Animation is nothing more than a change in position over time. We can reposition an image of a ball, for example, many time per second and it will give the impression of movement.

There are essentially 2 ways of doing this in Flash, we can move the object based on the current frame, or we can do it based on time. In an ideal world both would give the same effect, but in the real world computers have overheads, and Flash games won’t always run at exactly the framerate we set.

While time based animation is slightly trickier to understand than frame based animation, it’s still a fairly easy concept to get your head around, and the advantages are obvious – your game will still look and behave as it should no matter what speed the computer is running at, and how many other tasks are going on in the background!

Let’s take a look at a quick example to illustrate this. We’ll take a simple circle to be our ball, we’ll use a framerate of just 10FPS, a stage size of 600×600 pixels, and we’ll move the ball so it appears to drop from the top of the stage to the bottom in 2 seconds…

To do this with frame based animation we would simply increase the Y position of the ball by 30 pixels per frame (at 10 FPS we will be covering the 600 pixels in 20 frames, so 600/20=30).

So we would run code like this on every frame:

ball.y += 30;

Now all being well, the ball will move 30 pixels each frame, and after 2 seconds the ball would fall off the bottom of the stage and out of view. However, in the real world it’s quite possible for something to happen which causes the framerate to momentarily drop. Perhaps another open program is performing a function, maybe the user is checking an email on a second monitor, or anti-virus software has kicked in for a routine scan.

If this happens, the ball may only be 70% of the way down the screen at the end of 2 seconds. Now in such a simple example that wouldn’t really matter, but in a game situation the player will notice this slowdown and it will detract from the experience.

Time based animation on the other hand doesn’t move the object by a set amount each frame. Rather, each frame it will calculate the new position of the object based on velocity and time, correctly positioning it even if there has been a slowdown

Again we would run this code on every frame:

var timeFrame:int = getTimer() - oldTime;
oldTime+=timeFrame;
ball.y += ballSpeed*timeFrame;

This calculates the amount of time passed (in milliseconds) since the last frame, then positions the object based on how far it would have moved in that time period.

Now if a frame comes later than it should (due to slowdown) the ball will simply be shown slightly further down, in the correct position. This leads to smoother, more realistic animation, and games which feel responsive and look great, even on slower computers!

Here’s a Flash movie to show this in a working example. It’s running at 30FPS and is 400 pixels in height. The ball on the left is being moved by 10 pixels per frame (which should be 300 pixels per second), while the right hand ball uses time based animation, and is actually being moved at 300 pixels per second (1000 milliseconds, divided by the framerate of 30, multiplied by 0.3 gives 10 pixels per second, the same speed as ball 1)…

In an ideal world both should look identical, but what you’ll see is the left hand ball falls behind (click restart to put them both in alignment again!)

Here’s the actionscript so you can see exactly what’s going on:

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
var oldTime:int = 0;

addEventListener(Event.ENTER_FRAME, moveBalls);
restart.addEventListener(MouseEvent.MOUSE_DOWN, restartBalls);

function moveBalls(evt:Event) {
   
    // Ball1 = Frame based animation
    if(ball1.y>400) {
        ball1.y=0;
    } else {
        ball1.y+=10;
    }
   
    // Ball2 = Time based animation
    if(ball2.y>400) {
        ball2.y=0;
    } else {
        var timeFrame:int = getTimer() - oldTime;
        oldTime+=timeFrame;
        ball2.y+=0.3*timeFrame;
    }
   
}

function restartBalls(e:MouseEvent) {
    ball1.y=0;
    ball2.y=0;
}

The slower your computer, or the more processes you have running the more noticeable this difference will be. Now, note that this is simply moving 2 circles on the screen – imagine if we were controlling 10 or 20 sprites, a scrolling background, and a number of effects!

As you can see, time based animation is a much better way of moving game objects on screen, and once you get the hang of it you’ll never go back to frame based animation again!

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!

« Previous Entries