This tutorial is the third part in a series on game development with AS3. We will pick up where we left of in the last tutorial which can be found here: ActionScript 3 101 : Game Development part 2
In the previous tutorial we made a MovieClip of a ball move back and forth by pressing the left and right arrow keys on the keyboard. We accomplished this through the use of a variables, functions and events. In this tutorial we will continue to modify our existing code by adding a couple new functions and create something that will begin to resemble an actual game.
The Swap:
The first thing we need to do and swap out the ball artwork with a spaceship graphic. The graphic included with the source is the same dimensions as the ball, which was 72 x 72 pixels. You can use the one in the source code below ( just copy it into your project and delete the ball) or build your own.

The Stage:
To get everything ready for this round of edits, we need to rearrange a few things and increase the size the of the stage.The new size for the stage will be 600 x 600 pixels. To complete the space theme, a black background is required, later we can add a star field and possibly a nebula to make it look really cool, but for now a solid black background will be sufficient.

For the final visual update, please move the spaceship near the bottom center of the stage so it looks like it’s ready to attach something.

Updating the Code:
The visual updates we have just completed require modifications to the existing actionScript to keeps things functioning correctly. Click on the first frame of the actions layer to make the updates in the Actions Panel.
1. Find and Replace “ball” with “ship”.
With the visual change from ball to ship, we should update our code to match. It’s not a necessity, but will help in understanding our code going forward. Use Find and Replace to replace the string “ball” with “ship” in the Actions panel.

This will also require an update to the name of the ball instance on the stage, from “ball” to “ship” in the Properties Panel.

2. The Stage is now wider, updating the “boundsRight” variable will allow the spaceship to move all the way to the new width.
// right x of the stage var boundsRight:Number = 505; |
3. Updating the position of the ship requires an update to the “moveX” variable, now the ship’s movement starts from the ship’s current position.
// the current x position of the ball. var moveX:Number = ship.x; |
Let’s test what we have. The functionality is the same, but man does it look cool.
If your version does not look or function like this demo, please go back over the previous steps to make sure nothing was skipped.
Even More Cool:
With a bit more code and using the foundation we’ve already created, we can make this ship fire plasma projectiles. Now we’re talkin’!
Plasma Projectiles:
The included ship has two guns, one on each wing, so we will be demoing shooting two plasma balls at a time. Feel free to make up your own gun configurations and deviate from this tutorial as much as you feel comfortable.
Let’s create the graphics, these plasma balls were made from a blue radial gradient. #09B1FF with 100% alpha in the center and #027BD6 with 0% alpha at the edge. A little highlight circle was added as well as, a little rim light at the bottom to give it depth. #95E9F3 with 65% alpha for the highlight and #5F91FA with 30% alpha for the rim.

If your shapes that make up the plasma balls are drawing objects (not broken all the way down) then you can easily duplicate and slide over a copy. Otherwise you may need to group all your shapes before making the duplicate.
The last step is to make the plasma balls longer than tall, the oval shape looks a little better when in motion.
Convert the plasma balls into a symbol, a MovieClip named “ShipBomb” to be exact. While you are in the Convert to Symbol dialog box, select the Export for ActionScript check box. You can do this later by accessing the MovieClips properties in the library if needed.
When you click OK, you should receive the following “class could not be found…” message. This is Fine, click OK and continue. We will get into classes more in the next tutorial, but for now, this message is telling us that there is not an external class found to be associated with this new class, so Flash will just create the new class as is.

A MovieClip is a class, and ShipBomb is a class that extends the functionality of MovieClip, so now we can use this with our actionScript.

Making Plasma Fly:
Inside the ShipBomb MovieClip, we will add the following actionScript in the Actions Panel.
1. Importing the Event class, this should should automatically when you add the frameHandler function below, but only if you type it out, if you copy and paste, you will have to add it manually.
import flash.events.Event; |
Tip: Learn more more tips importing classes in Flash and Flash Builder.
2. Create two new variables:
// To which y coordinate the bomb should travel? var minY:Number = 0; // How fast should the bomb travel? <pre lang="actionscript"> var speed:Number = 10; |
3. Create an event handler for the enter frame event.
function frameHandler(ev:Event):void{ // On every frame decrease the y position by the amount of speed, moving this upward. this.y -= speed; // If the y position is less the the minimum y coordinate, clean up and remove itself. if(this.y < minY){ this.removeEventListener(Event.ENTER_FRAME, frameHandler); this.parent.removeChild(this); } } |
4. Add the event listener
this.addEventListener(Event.ENTER_FRAME, frameHandler); |
If the ShipBomb MovieClip is still on the stage, try a quick test, it should move up the screen and disappear.
After the test, please remove the instance of ShipBomb from the stage.
Controlling the Weapon:
Adding in the previous code was not so bad and finishing things up will be just as easy.
1. Create a function in the root of the fla. On the actions layer, first frame, enter the following code into the Actions Panel.
// ship fires bomb function fireBomb():void{ // create a new instance of ShipBomb var bomb:ShipBomb = new ShipBomb(); // set the bombs y position equal to the ships y position. bomb.y = ship.y; // set the bombs x position equal to the ships x position, plus 10, // to align the plasma balls to the guns. bomb.x = ship.x + 10; // cache the bomb as a bitmap to help performance. bomb.cacheAsBitmap = true; // add the bomb to the stage addChild(bomb); } |
2. The keyboard events are already being handled by the function called keyHandler. A few tweaks and additions to this function and we will have a ship that fires.
// if the key is up and that key is the same as the currently pressed key // ignore the key press if it is the space bar, or keyCode 32. if(!keyPressed && currentKey == ev.keyCode && ev.keyCode != 32){ //stop movement moveXKeyDown = false; return; } |
3. Down, near the end of the keyHandler function add the following conditional and call to the fireBomb function.
// if the key is pressed and it is the spacebar, fire the bomb. if(keyPressed && ev.keyCode == 32){ fireBomb(); } |
Now do a test to see what we have.
Hopefully your version works very similar to this sample. You may want to tweak the x or y starting position of the bomb to make sure it is aligned properly.
Download the Source code here.
Complete Code:
The SpaceGame Fla frame 1:
import flash.events.KeyboardEvent; /** CONFIG **/ // left x of the stage var boundsLeft:Number = 20; // right x of the stage var boundsRight:Number = 505; // base speed or distance to move the ship var maxSpeed:Number = 10; /** RUNTIME VAIRABLES **/ // how far the ship travels each frame var speed = maxSpeed; // the current x position of the ship. var moveX:Number = ship.x; // the keyboard is pressed var moveXKeyDown:Boolean; // which keyCode is currently down. var currentKey:int; /** EVENT HANDLERS **/ // Enter Frame Event handler function frameHandler(ev:Event):void{ if(moveXKeyDown){ // increase the ship x position by the value of speed moveX += speed; // if ship x reaches right bounds if(moveX >= boundsRight){ // stop movement moveXKeyDown = false; // set the ship x position to the right bounds moveX = boundsRight; } // if ship x reaches left bounds if(moveX <= boundsLeft){ // stop movement moveXKeyDown = false; // set the ship x position to the left bounds moveX = boundsLeft; } // update the ship's x property to equal moveX ship.x = moveX; } } // handle keyboard key presses function keyHandler(ev:KeyboardEvent):void{ // set moveVariable true or false depending on the keyboardEvent type var keyPressed:Boolean = ev.type == KeyboardEvent.KEY_DOWN; // if the key is up and that key is the same as the currently pressed key if(!keyPressed && currentKey == ev.keyCode && ev.keyCode != 32){ //stop movement moveXKeyDown = false; return; } // which key was pressed and is it a key down if(ev.keyCode == 37 && keyPressed){ // left arrow key down - move left // set speed to negitive speed = -maxSpeed; // set current key code currentKey = ev.keyCode; // start move moveXKeyDown = true; } if(ev.keyCode == 39 && keyPressed){ // right arrow key - move right // set speed to positive speed = maxSpeed; // set current key code currentKey = ev.keyCode; // start move moveXKeyDown = true; } if(keyPressed && ev.keyCode == 32){ fireBomb(); } } // ship fires bomb function fireBomb():void{ // create a new instance of ShipBomb var bomb:ShipBomb = new ShipBomb(); // set the bombs y position equal to the ships y position. bomb.y = ship.y; // set the bombs x position equal to the ships x position, plus 10, // to align the plasma balls to the guns. bomb.x = ship.x + 10; // cache the bomb as a bitmap to help performance. bomb.cacheAsBitmap = true; // add the bomb to the stage addChild(bomb); } /** EVENT LISTENERS **/ // setup event listener for the ENTER_FRAME event type // point the event to trigger the "frameHandler" funciton above addEventListener(Event.ENTER_FRAME, frameHandler); // setup event listeners for the KEY_DOWN and KEY_UP types of the KeyboardEvent stage.addEventListener(KeyboardEvent.KEY_DOWN, keyHandler); stage.addEventListener(KeyboardEvent.KEY_UP, keyHandler); // stop this timeline stop(); |
ShipBomb MovieClip frame 1:
import flash.events.Event; var minY:Number = 0; // To which y coordinate the bomb should travel? var speed:Number = 10; // How fast should the bomb travel? function frameHandler(ev:Event):void{ // On every frame decrease the y position by the amount of speed, moving this upward. this.y -= speed; // If the y position is less than the minimum y coordinate, clean up and remove itself. if(this.y < minY){ this.removeEventListener(Event.ENTER_FRAME, frameHandler); this.parent.removeChild(this); } } // add enter frame event listener this.addEventListener(Event.ENTER_FRAME, frameHandler); stop(); |
Where To Go From Here?
We have covered the basics in both code and logic for making things move and controlling these objects with the keyboard. See how for you can go with figuring out how to add bombs falling from the top of the screen. In the next tutorial we will go over classes and create some aliens for us to shot at. They will be shooting back at us.

Get as far as you can, work through the problems and see what you come up with. There are no wrong answers as long as it works.
For final source code which includes alien bombs falling, click here.
Another thing to do is mess with the Frame Rate of the Fla, see what kind of performance you can get. An Adjustment to the speed variables may be required to get things working just so. Most action games shot for 60 frames per second.
| 1 Comment » | facebook:
RSS feed for comments on this post. TrackBack URL
Great Flash game tutorial! Did you know that if you hold down the spacebar it fires and you see a solid line of bullets? Thanks for posting this tutorial!
Comment by Pat — December 14, 2011 @ 10:16 pm