Tutorials

February 5, 2009

AS3 Flash Games for Beginners: Adding Library Objects to Stage with AS3

More articles by »
Written by: Par
Tags: , , , ,
basics1_tn

Share on TwitterShare on TumblrSubmit to StumbleUponSave on DeliciousDigg ThisSubmit to reddit

This is the first series on As Gamer that will take you through the basics of ActionScript 3.0 Development of a Flash Game.  The goal is to give you a fundamental overview of using Flash CS3 or better to develop a game.  If you are not a programmer follow along closely and I’ll try to make everything relatively simple. However, if understanding the reasoning behind conditional statements is not obvious, you may want to look into purchasing a programming book at your local bookstore. That said, this series will be very simple, but extremely effective at teaching you the principles behind the average flash game.

First of all you need:

  • Flash! of course, this isn’t going to work without it.  So if you don’t have the program, head to Adobe Flash’s website and download Adobe Flash CS4 trial version. It’s the full thing and it should work for about 30 days before expiration.
  • Flash Develop 3 (optional), I love this program. It’s clean, simple, and works great for organizing your as classes. But if you’d rather use Flash’s built in IDE, that’s fine as well. Whichever you prefer. But download Flash Develop here if you want.

Alright so this first game we are going to make is a simple space shooter, kinda like Space Invaders… Oh no! You’ve seen a billion tutorials like this before. No, I promise to make this a little more enjoyable, a lot more informative, and AS3.  If you’re wondering why AS3 is so great? Well, it’s faster first of all (than AS2). And if you are making a game, speed is a necessity. So stay with me and you’ll see how AS3 is going to make a simple space game that we can build on and make something great.

Step 1 : Setting up the Flash Document and Basic Drawing

Now open Flash and create a new ActionScript 3.0 Document, click the size button in the bottom properties tab,  and set it’s width to 500, height to 400, and frames per second to 30 (refer to image below). Then OK.  Excellent, now let’s create a basic background for our game.  So grab the Rectangle Tool (R) and paint a square that covers the white of our stage (The white area is the visible area in the flash game or application.) Make sure  Object Drawing (J) is off (It’s the little icon in the Tools Window (CTRL + F2) beside the magnet snap to objects icon.) If Object Drawing is on, you will not be able to edit the color of your Rectangle unless you jump into the object.  I’m going to make my rectangle fade from black to navy. To recolor your rectangle just grab the Paint Bucket Tool (K) and set your color in the Color Tab (SHIFT + F9). The color tab should be in a menu on the right by default.  Once your color is set, click the paint bucket on the rectangle and it will change color. If you have selected a gradient color then you can click and drag the paint bucket to get your desired effect. Now make sure we name our layer to background. It’s in the Timeline (CTRL+ALT+T) at the top of you’re Flash Application. Double click the layer name (Layer 1) and rename it to background. This as nothing to do with our code, but will help us to understand what artwork is where if we come back to this file later.

The Document Properties... the title and description and not important; however, Dimensions and Frame Rate are.

The Document Properties… the title and description and not important; however, Dimensions and Frame Rate are.

My current stage. Simply the navy to black rectangle.

My current stage. Simply the navy to black rectangle.

Step 2 : Making our ship

Now let’s make our ship.  Create a new layer name and name it ship.  Lock your Background layer by clicking the second dot which is under the lock icon.  This prevents us from drawing on the background layer and messing it up.

Draw your ship however you want. Just make it stay within 50×50 pixels. I drew three triangles and arranged them together. Now select your ship, you may need to click your ship layer once to highlight all your artwork, and right click. Goto Convert to Symbol… Name it ship, make sure it is a MovieClip and the Registration is set to the center.

The Registration’s location determines the x and y value of our MovieClip. Any objects in your games from now on, you will want to be conscientious of the Registration, dead center is not always the best solution, but for our ships case, it will work great.

Now your ship should appear in the Library (CTRL+L), so delete it from the stage and remove the ship layer you created.  The next time your ship is on the stage, it will be via ActionScript.

Convert to Symbol box

Convert to Symbol box

Step 3: Linking our Scene and MovieClip to Actionscript 3.0 Classes

Actionscript 3 flash files now have the ability to setup a document class.  The document class is a class that will be automatically ran when the compiled flash game is executed. This prevents us from needing to write code in the .fla file.  To find the document class, you need to deselect anything on the stage and in the Properties Box (CTRL+F3) the document class will be below the frames per second and background box.  If you can’t see the document class, you will need to resize your properties box. Simply grab between the Properties box and the Stage and pull the properties window up.

Now, name your document class “com.asgamer.basics1.Engine” without quotes. When you click out of the box Flash will complain that the document class doesn’t exist, that’s fine, we’ll be making it in a few.

Now as an explanation, com.asgamer.basics1 is our package. From a file structure perspective that’s the folders from our basics1.fla file to our document class. basics1 is in the folder asgamer, asgamer is in the folder com, and com is in the same folder as our basics1.fla file.  The reasoning behind the package name is com is my domain name extension, asgamer is my domain name, basics1 is the project name, and Engine is the class.  This means if Bob at boblikesgamesalot.com creates an Engine class his won’t conflict with mine because his package would be com.boblikesgamesalot.basics1.

Now let’s setup our class for our ship.  Just right click your ship in your library and go to Linkage…  Click the Export for Actionscript check box and new options will become available.  Class will be the class that runs for our Ship, by default if you don’t change the linkage when Flash is compiled it will create a class for your Ship that is based on MovieClip. Our Base Class is defaulted to flash.display.MovieClip leave it alone, that’s perfectly fine for now and in most cases.  As for our Class, name it com.asgamer.basics1.Ship and click OK.  It will say it doesn’t exist again… Ignore it, we’ll fix that next.

Our document class.

Our document class.

Linkage for our Ship. Leave Export in first frame checked, it defeats the purpose of a preloader, but we'll discuss this later.

Linkage for our Ship. Leave Export in first frame checked, it defeats the purpose of a preloader, but we'll discuss this later.

Step 4: Setting up our ActionScript 3.0 Classes

First we will address the document class. So using Flash Develop or Flash itself, create a new as file called Engine in your com/asgamer/basics1 folder. Add this code inside the as file.

//our package... simply put, the directory structure to this file
package com.asgamer.basics1
{
	//list of our imports these are classes we need in order to
	//run our application.
	import flash.display.MovieClip;
	import flash.display.Stage;
 
	//our Engine class it extends MovieClip
	public class Engine extends MovieClip
	{
 
		//our constructor function. This runs when an object of
		//the class is created
		public function Engine()
		{
 
		}
 
	}
 
}

Your basic class structure. Let’s examine it:

  • import flash.display.MovieClip; Imports allow us to take the code from another class and use it in ours.  In this case Engine extends MovieClip so in order to access our MovieClip properties Flash needs to know what properties Engine should have. So we import MovieClip and it’s ready to go.
  • public function Engine(). Anytime in AS3 that a class has a function with the same name, it is the constructor function. A constructor function is ran when a new object of a class is created.  So our public function Engine is ran when the Engine object is created (which is made when the flash game is ran because Engine is the document class.)

Now let’s write code for our ship.  Create a new as file named Ship at the same location as Engine.  Enter this code into it.

package com.asgamer.basics1
{
 
	import flash.display.MovieClip;
 
	public class Ship extends MovieClip
	{
 
		public function Ship()
		{
 
		}
 
	}
 
}

Look familar?  Yeah it’s the same basic structure.  As a note, you don’t have to add the constructor function, if you decide you don’t need your object to do anything at creation time, then don’t add the constructor function. That’s perfectly fine.

As another note, while it looks like our Ship and Engine class on have one function inside them, that’s not entirely true. All the functions and properties of MovieClip are in them.  For example we have access to the properties x and y from MovieClip and the functions addChild and removeChild.  And MovieClip actually inherited these properties from indirectly extending DisplayObject and these functions from the class DisplayObjectContainer.  You can repeatively make classes extend other classes where it is necessary. If you don’t have a good reason for doing it, it’s probably not necessary and more confusing than useful.

None the least, our Ship class has an x and y property that it has inherited and we can use and we will be taking advantage of it.

Step 6: Making our Ship appear on the Stage once again with ActionScript 3.0

Alright return to our Engine class and inside the Engine function add this:

			//create an object of our ship from the Ship class
			var ourShip:Ship = new Ship();
			//add it to the display list
			stage.addChild(ourShip);

The Breakdown:

  • var ourShip:Ship = new Ship(); Remember when we linked our Ship in Flash to be com.asgamer.basics1.Ship. Well to make an object of our ship all we have to do is this line. var denotes this is a variable. ourShip is the variable name. :Ship lets Flash know this is a variable of the type Ship. new means we are making an object of this class. and Ship() is the class we are making an object of.  The parenthesis are empty because our Ship constructor doesn’t take any parameters.
  • stage.addChild(ourShip); All movieclips have a stage property, which depending on the situation references the document’s stage. In this case we are accessing Engine’s stage property.  The stage property is immediately accessible through the document class. Other DisplayObject classes (anything you create from the library) also have a stage property. Problem is, this stage property is null until the DisplayObject is directly or indirectly added to the stage. If you need to access the stage from classes other that the Document Class it may be easier to pass the stage into the classes that need it (We will talk about this later). None the least, the Stage class extends DisplayObjectContainer and therefore also has the addChild function. The addChild function takes one parameter; the DisplayObject it needs to display. In our case, we want to display ourShip.

Now test your Game. Go into Flash and goto Control -> Test Movie (CTRL+ENTER). If it runs great!, if not you messed up somewhere. You should see something like this:

You should see your spaceship in the top left corner… Why? Because we need to move it’s x and y to make it center. Currently it’s being loaded at the default x and y of zero. Let’s change that to dead center.  Update your Engines constructor to look like this:

		public function Engine()
		{
			//create an object of our ship from the Ship class
			var ourShip:Ship = new Ship();
			//add it to the display list
			stage.addChild(ourShip);
 
			ourShip.x = stage.stageWidth / 2;
			ourShip.y = stage.stageHeight / 2;
 
		}

The Breakdown:

  • .x is the horizontal coordinate of our ship. .y is the vertical. We set them equal to the stage’s width(this size of our document) divided by 2 and the stage’s height divided by 2. This should be dead center. And if ourShip has a registration point in the center, ourShip will definitely be centered.

Test your Game again, it should look something like this.

Excellent job, now you know how to add a library movieclip to a flash game via Actionscript. Go ahead create another variable called yourShip and add it to the stage with ourShip. You can create as many as you want. Give it a go.

And better yet, make your background a Class and add it dynamically with Actionscript as well.

Here’s the completed source: As Gamer Basics 1 Zip Archive

Continue to Step 2: Character Movement / Handling Multiple Keypresses

Similar Posts:


Share on TwitterShare on TumblrSubmit to StumbleUponSave on DeliciousDigg ThisSubmit to reddit


About the Author

Par
Hey! Don't be surprised, I'm a flash developer. While Flash is definitely one of my favorite languages to develop in, most of all I just like making games. If you want to see the games I've developed so far head over to my website, DigitallyBold, in the link below. If you want to know more about what I'm working on now and in the future be sure to follow me on twitter.




61 Comments


 
 

  1. mitul

    If you make a video tutorial for this. I would be glade full to you


  2. farhan

    Its Awosome for Beginnerr’s and thank you so much for tutorials


  3. xx

    stage.stageWidth does not work on Internet Explorer (works on Chrome and Firefox). So we add a sprite or movieclip background, name it bg and modify the upper code to:
    ourShip.x = bg.width / 2;
    ourShip.y = bg.height / 2;


 
 



Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">


Advertisement