Take a look through this Premium Tutorial and create an entertaining falling platforms game using Flash and ActionScript 3.0. Don't hit the purple platforms or move outside of the screen, or you'll lose a life!
Step 1: Brief Overview
Using the Flash drawing tools we'll create a good looking graphic interface that will be powered by several ActionScript 3 classes.
The user will be able to move a character across the stage and the platforms, you can modify the parameters in the class to customize the game.
Step 2: Flash Document Settings
Open Flash and create a 320 pixels wide, 480 pixels tall document. Set the Frame rate to 24fps.

Step 3: Interface

A colorful nice looking interface will be displayed, this involves multiple shapes, buttons, sounds and more.
Continue to the next steps to learn how to create this GUI.
Step 4: Background

Select the Rectangle Tool (R) to create a 320x480px #DEBDA0 rectangle and center it in the stage. Duplicate the previous shape and change the width to 2px and its color to #C3A287, duplicate the shape (Cmd + D) several times and move each 2px to the right to get the result shown above.
Step 5: Menu Screen

Select the Text Tool (T), choose a good looking font, and write your game title. I used this format: Candara Bold, 80pt, #746253. You can also add the player and platform graphics that we'll be creating in the next steps.
Use the same technique to create two buttons, align them to the center and name them startB and creditsB. Convert all to a MovieClip and set its instance name to menuView.
Step 6: Score & Lives

This will be the GameView. Add the background MC to the stage and create two Dynamic TextFields and place them as shown in the image. You can also add some simple shapes behind the TextFields to make the text more clear.
Step 7: Player

Use the Rectangle Primitive Tool (R) to create a 30x30px square and fill it with #CC6600. Duplicate the shape, change its size to 28x28px and use this gradient fill: #F9D03 to #EA7736. You can add an icon or letter to identify your character, I've used the a from the ActiveTuts+ logo.
Lastly, select the bottom part of the shape (as shown in the image) convert it to MovieClip and name it hArea, this will be really useful for avoiding unwanted collisions with the blocks. Select all the shapes and convert them to a single MC; name it Player and mark the Export for ActionScript box.
Step 8: Blocks

Use the same technique used in the last step to create two 60x14px blocks, convert them to MC, name the grey one Block and the purple one BadBlock. Don't forget to mark the Export for ActionScript box.
Step 9: Alert

An alert will be shown when you lose all your lives, it will show the final score you reached. Use the Rectangle Primitive Tool to create it and add the filter shown in the image for a better look. Set its instance name to AlertView and mark the Export for ActionScript box.
Step 10: Credits

This screen will be easy to make as we already have all the graphics. Set its instance name to CreditsView and mark the Export for ActionScript box.
Step 11: Tween Nano

We'll use a different tween engine from the default included in Flash, this will increase performance as well as being easier to use.
You can download Tween Nano from its official website. For info on installing it, read this tutorial.
Step 12: Soungle

We'll use Sound Effects to enhance the feeling of the game (in this case to let the player know when they have lost a life), you can find the sound used in this example on Soungle.com using the keyword blip. Save the sound in your Library with a Class Name of Blip.
Step 13: Create a new ActionScript Class

Create a new (Cmd + N) ActionScript 3.0 Class and save it as Main.as in your class folder.
Step 14: Class Structure
Create your basic class structure to begin writing your code.
package { import flash.display.Sprite; public class Main extends Sprite { public function Main():void { // constructor code } } }
Step 15: Required Classes
These are the classes we'll need to import for our class to work, the import
directive makes externally defined classes and packages available to your code.
import flash.display.Sprite; import flash.events.Event; import flash.events.KeyboardEvent; import flash.events.TimerEvent; import flash.utils.Timer; import flash.events.MouseEvent; import flash.net.navigateToURL; import flash.net.URLRequest; import com.greensock.TweenNano; import com.greensock.easing.Elastic;
Step 16: Variables
These are the variables we'll use, read the comments in the code to know more about them, some of their names are self explaining so there will be no comment there.
private var blocks:Vector.<Sprite> = new Vector.<Sprite>(); // A vector to store the moving blocks private var player:Player = new Player(); private var gravity:int = 3; //The gravity var used to move the player and blocks private var moveLeft:Boolean = false; //store the player direction private var moveRight:Boolean = false; private var blockTimer:Timer = new Timer(800); //time to wait before a new block is generated private var life:Life; private var lives:int = 3; private var lifeTimer:Timer = new Timer(8000); //time to wait before a new life is shown private var blip:Blip = new Blip(); //A sound instance
Step 17: Constructor
The constructor is a function that runs when an object is created from a class, this code is the first to execute when you make an instance of an object, or the first to run when the project has loaded if it is in the Document Class.
It calls the necessary functions to start the game. Check those functions in the next steps.
public final function Main():void { initialListeners('add'); }
Step 18: Initial Listeners
We'll start by adding the mouse listeners to the buttons in the menu view, these will take us to the game screen or the credits screen.
private final function initialListeners(action:String = 'add'):void { if(action == 'add') { menuView.startB.addEventListener(MouseEvent.MOUSE_UP, gameView); menuView.creditsB.addEventListener(MouseEvent.MOUSE_UP, showCreditsView); } }
Step 19: Game View
When the Start button is pressed, the focus is set to stage in order to receive the keyboard actions to move the player, then the Menu view is tweened and removed.
private final function gameView(e:MouseEvent):void { /* Focus Stage */ stage.focus = stage; /* Remove MenuView, Start Game */ TweenNano.to( menuView, 0.5, { y:-menuView.height, onComplete: function():void{ removeChild(menuView); menuView = null; addInitialBlocks(); } } ); }
Step 20: Show Credits
The credits screen is shown when the user clicks the credits button, a mouse listener is added to the full MC to remove it.
private final function showCreditsView(e:MouseEvent):void { var credits:CreditsView = new CreditsView(); addChild(credits); TweenNano.from(credits, 0.4, {x:stage.stageWidth}); credits.addEventListener( MouseEvent.MOUSE_UP, function():void{ TweenNano.to( credits, 0.4, { x:stage.stageWidth, onComplete: function():void{ removeChild(credits); credits = null; } } ); } ); }
Step 21: Create Initial Blocks
The following code adds the blocks specified in the parameter at a random position, it will also call the function to add the player to the stage.
private final function addInitialBlocks(n:int = 3):void { for(var i:int = 0; i < n; i++) { var block:Block = new Block(); block.x = Math.random() * (stage.stageWidth - block.width); block.y = (stage.stageHeight * 0.5) + Math.random() * (stage.stageHeight * 0.5); addChild(block); blocks.push(block); } addPlayer(); }
Step 22: Add Player
The player will be added when the initial blocks are on the stage. It will appear in the center X of the stage.
private final function addPlayer():void { player.x = (stage.stageWidth * 0.5) - (player.width * 0.5); player.y = player.height; addChild(player); gameListeners(); }
Step 23: Move Player
The following code will set the appropiate movement variable value to true or false depending on which key was pressed, then the variable will be checked every frame (in another function). This will make the player move according to that variable.
private final function movePlayer(e:KeyboardEvent):void { if(e.keyCode == 37) { moveRight = false; moveLeft = true; } else if(e.keyCode == 39) { moveLeft = false; moveRight = true; } }
Step 24: Stop Player
When the arrow keys are released the appropiate variable is set to false
to stop movement.
private final function stopPlayer(e:KeyboardEvent):void { if(e.keyCode == 37) { moveLeft = false; } else if(e.keyCode == 39) { moveRight = false; } }
Step 25: Add Blocks
This function is called by a Timer; it will calculate a random integer from 0 to 3, when the result equals 0, a bad block will be added, if the result is different than 0, a normal block will be added. The blocks are added to a Vector property called blocks
, this way we are able to access them outside this function.
private final function addBlock(e:TimerEvent):void { var r:int = Math.floor(Math.random() * 4); if(r != 0) { var block:Block = new Block(); block.x = Math.random() * (stage.stageWidth - block.width); block.y = stage.stageHeight + block.height; addChild(block); blocks.push(block); } else { var badBlock:BadBlock = new BadBlock(); badBlock.name = 'bad'; badBlock.x = Math.random() * (stage.stageWidth - badBlock.width); badBlock.y = stage.stageHeight + badBlock.height; addChild(badBlock); blocks.push(badBlock); } }
Step 26: Add Life
Another timed function, a life graphic will be added when the timer is complete. The life position will be the last block in the vector - 1.
private final function addLife(e:TimerEvent):void { life = new Life(); life.x = blocks[blocks.length - 1].x; life.y = blocks[blocks.length - 1].y - life.height; addChild(life); }
Step 27: Game Listeners
This function adds and removes the necessary listeners to start the game.
private final function gameListeners(action:String = 'add'):void { if(action == 'add') { stage.addEventListener(KeyboardEvent.KEY_DOWN, movePlayer); stage.addEventListener(KeyboardEvent.KEY_UP, stopPlayer); stage.addEventListener(Event.ENTER_FRAME, update); blockTimer.addEventListener(TimerEvent.TIMER, addBlock); blockTimer.start(); lifeTimer.addEventListener(TimerEvent.TIMER, addLife); lifeTimer.start(); } else { stage.removeEventListener(KeyboardEvent.KEY_DOWN, movePlayer); stage.removeEventListener(KeyboardEvent.KEY_UP, stopPlayer); stage.removeEventListener(Event.ENTER_FRAME, update); blockTimer.removeEventListener(TimerEvent.TIMER, addBlock); blockTimer.stop(); lifeTimer.removeEventListener(TimerEvent.TIMER, addLife); lifeTimer.stop(); } }
Step 28: Animate Lives
When the player loses a life, a little animation will be shown in the lives textfield and a sound will be played to warn the user.
private final function animateLives():void { TweenNano.from( livesTF, 0.8, { x:livesTF.x - 3, ease: Elastic.easeOut } ); blip.play(); }
Step 29: Controls
In this part we start the main function of the game, this function will be executed every frame.
The next lines of code check the movement variables, if true, the player will be moved.
private final function update(e:Event):void { /* Controls */ if(moveLeft) { player.x -= 4; } else if(moveRight) { player.x += 4; }
Step 30: Screen Boundaries
This code creates invisible walls on the sides of the stage to prevent the player from going out of it.
/* Screen Boundaries */ if(player.x <= 0) //Left { player.x = 0; } else if(player.x >= (stage.stageWidth - player.width)) //Right { player.x = (stage.stageWidth - player.width); }
Step 31: Player Gravity
The player is pushed down by the gravity variable.
/* Player Gravity */ player.y += gravity;
Step 32: Block Collisions
The next lines check for collisions between the player and the blocks. When the player collides with a normal block it stays on top of it. When a bad block is hit, a life is lost and the player is relocated.
for(var i:int = 0; i < blocks.length; i++) { if(player.hArea.hitTestObject(blocks[i]) && blocks[i].name == 'bad') { for(var j:int = 3; j < blocks.length; j++) { if(blocks[j].name != 'bad') { player.x = blocks[j].x; player.y = blocks[j].y - player.height; lives--; animateLives(); livesTF.text = 'x' + String(lives); j = blocks.length; } } } if(player.hArea.hitTestObject(blocks[i])) { player.y = blocks[i].y - (player.height + 3); }
Step 33: Blocks Gravity
Gravity affects the blocks too, but in the opposite direction.
blocks[i].y -= gravity;
Step 34: Remove Offstage Blocks
The blocks are destroyed when they are no longer visible on stage.
if(blocks[i].y < -blocks[i].height) { removeChild(blocks[i]); blocks[i] = null; blocks.splice(i, 1); }
Step 35: Score
The game score raises every frame, this code changes the textfield to reflect that.
scoreTF.text = String(int(scoreTF.text) + 1);
Step 36: Lives
The following lines handle the life graphic and variables.
If a Life (a 1-Up) is on the stage, it will be moved upwards, and removed if it's hit by the player or is no longer visible on stage.
if(life != null) { life.y -= gravity; /* Remove +Life */ if(life.y < 0) { removeChild(life); life = null; } } /* Grab +Life */ if(life != null && player.hitTestObject(life)) { removeChild(life); life = null; lives++; livesTF.text = 'x' + String(lives); } /* Lose Lives */ if(player.y > stage.stageHeight || player.y < -5) { player.x = blocks[3].x; player.y = blocks[3].y - player.height; lives--; animateLives() livesTF.text = 'x' + String(lives); }
Step 37: Game Over
When theplayer is out of lives, the showAlert()
function is called. This function will stop the game and reveal the final score.
if(lives < 0) { showAlert(); }
Step 38: Levels
You can add as many levels as you want, this is an example of how you can add a level.
When the score reached 500 the gravity increases by 1, this will make the game move faster and harder to land on the platforms, it also reduces the time the lives are added.
if(int(scoreTF.text) > 500 && int(scoreTF.text) < 502) { gravity = 4; lifeTimer = new Timer(12000); }
Try making the speed increase after every 500 points.
Step 39: Alert
This function will stop the game and reveal the final score, it also adds a mouse listener to reset the game when clicked.
private final function showAlert():void { gameListeners('rmv'); var alert:AlertView = new AlertView(); alert.x = stage.stageWidth * 0.5; alert.y = stage.stageHeight * 0.5; alert.scoreTF.text = scoreTF.text + '!'; livesTF.text = ''; alert.addEventListener(MouseEvent.MOUSE_UP, restart); addChild(alert); TweenNano.from( alert, 0.7, { y: -alert.height, ease:Elastic.easeOut } ); }
Step 40: Restart
The next function will reload the SWF, resetting all variables and methods and returning to the Menu Screen.
private final function restart(e:MouseEvent):void { navigateToURL(new URLRequest(stage.loaderInfo.url), '_level0'); }
Step 41: Set Main Class

Add the class name to the Class field in the Publish section of the Properties panel to associate the FLA with the Main document class.
Conclusion
You've created a very entertaining game, try to add your own features and graphics.
I hope you liked this tutorial, thank you for reading!
Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!
Translate this post