Create a Flash ball game using AS3
Ok... I think it's time to start talking about Actionscript 3. Even if AS2 is way to be dead, is becoming a bit obsolete... every new library like Box2DFlashAS3 only works in AS3, so sooner or later we must learn AS3.
Obviously I won't stop talking about AS2 until it's dead and stinking... but this tutorial is dedicated to AS3
I am going to create the same prototype explained at Flash game creation tutorial - part 1, just using AS3
The first thing you have to do, is creating the ball itself as a new object, and giving it the ball linkage name, as usual.
Then, in the Movie Properties panel, you must specify the document class. Also, in the Publish Settings panel, you must specify the path where you will save the class (called ClassPath) as shown in the image.

Now, you're ready to write your class file... click on the pencil next to your document class name and here it is the AS3 code:
-
package {
-
import flash.display.*;
-
import flash.events.*;
-
import flash.ui.*;
-
public class as3ball extends MovieClip {
-
var the_hero: Sprite = new ball();
-
var power = 0.3;
-
var friction = 0.95;
-
var xspeed = 0;
-
var yspeed = 0;
-
var up = false;
-
var down = false;
-
var left = false;
-
var right = false;
-
public function as3ball() {
-
addChild(the_hero);
-
the_hero.x = 250;
-
the_hero.y = 200;
-
stage.addEventListener(KeyboardEvent.KEY_DOWN, key_pressed);
-
stage.addEventListener(KeyboardEvent.KEY_UP, key_released);
-
addEventListener(Event.ENTER_FRAME, render);
-
}
-
function key_pressed(e:KeyboardEvent):void {
-
switch (e.keyCode) {
-
case Keyboard.UP :
-
up = true;
-
break;
-
case Keyboard.DOWN :
-
down = true;
-
break;
-
case Keyboard.LEFT :
-
left = true;
-
break;
-
case Keyboard.RIGHT :
-
right = true;
-
break;
-
}
-
}
-
function key_released(e:KeyboardEvent):void {
-
switch (e.keyCode) {
-
case Keyboard.UP :
-
up = false;
-
break;
-
case Keyboard.DOWN :
-
down = false;
-
break;
-
case Keyboard.LEFT :
-
left = false;
-
break;
-
case Keyboard.RIGHT :
-
right = false;
-
break;
-
}
-
}
-
private function render(e:Event):void {
-
if (up) {
-
yspeed -= power;
-
}
-
if (down) {
-
yspeed += power;
-
}
-
if (left) {
-
xspeed -= power;
-
}
-
if (right) {
-
xspeed += power;
-
}
-
xspeed *= friction;
-
yspeed *= friction;
-
the_hero.x += xspeed;
-
the_hero.y += yspeed;
-
}
-
}
-
}
Line 1: declaration of the package in which we are going to build our class. Normally the syntax would be package
Line 2: importing the package that contains the core classes that the Flash Player uses to build visual displays.
Line 3: importing the package containing the classes to manage events such as keyboard events, mouse events, and more
Line 4: importing the package that contains user interface classes, such as classes for interacting with the mouse and keyboard
Line 5: declaration of the main class. Class name must be the same as the name of the .as file
Line 6: declaring a new variable called the_hero as a Sprite type (think about the sprite as an AS2 movieclip), and assigning it the ball movieclip. From now on, we will refer to the_hero everytime we want to move the ball.
Lines 7-10: declaring speed, power and friction variables as seen in the AS2 tutorial
Lines 11-14: Declaring four boolean variables, one for each direction, and setting them to false. You will understand why I am doing this later in this tutorial
Line 15: Declaration of the main function. You know this is the main function because of its name... the same as the class. Naming the function this way will make it execute once the movie is loaded
Line 16: Adding the hero to stage. addChild is the AS3 method to see a display object appear on the Stage. In this case, it displays the the_hero sprite that contains the ball movieclip
Lines 17-18: Placing the_hero movieclip in the centre of the stage.
Line 19: Adding a listener for the KEY_DOWN event (a key is pressed) and calling the key_pressed function when the event is triggered
Event listeners, which are also called event handlers, are functions that Flash Player executes in response to specific events. In this case, the specific event is "a key is pressed", and the function to be executed is key_pressed. This function will be executed every time a key is pressed.
Line 20: Adding a listener for the KEY_UP event (a key is released) and calling the key_released function when the event is triggered
Line 21: Adding a listener for the ENTER_FRAME event (the beginning of a new frame, just like the old AS2 onEnterFrame) and calling the render function when the event is triggered
Line 23: Beginning of the function to be executed every time a key is pressed
Lines 24-37: Performing a switch with the keycode of the key pressed, setting to true the boolean variable corresponding to the arrow key pressed
Lines 39-53: Same thing for the key_pressed function, but the key_released sets to false the variable corresponding to the arrow key released
These two functions may seem useless, but they are the core of the script because I can't perform the old Key.isDown... I can only see when a key is pressed and when a key is released. And remember the player can press more than a key at the same time
Line 55: Function to be executed at every frame
Lines 56-71 follow the same rules seen at Flash game creation tutorial - part 1.
And here's the result:
As you can see, AS3 learning curve is a bit harder than AS2 one, but once you understand the basics, you can achieve results that are simply impossible to get with AS2
Hope this first tutorial will make you start using AS3 just like a lot of you said Flash game creation tutorial - part 1 made you start using AS2
Download the source code and give me feedback
Tell me what do you think about this post. I'll write better and better entries.
They can be easily customized to meet the unique requirements of your project.
22 Responses to “Create a Flash ball game using AS3”
Leave a Reply

Nice idea to do it in AS3, but one thing I don’t understand is why should you do it in AS3 when it has to be done is so much more code when in AS2 its much more simpler?
Dose it run the code faster or something?
Just wondering..
-Hawdon
to start learning AS3…
Hey great to see you finally doing stuff in AS3. I think AS3 is much much simpler and easier to use than AS2. I found your site when looking for a way to make a movieclip face the mouse, and have been watching your posts since then.
Anyway, can’t wait to see what you come up with! I have a REALLY good Input class that I can send you if you would like. It makes handling input very easy.
It’s great to see you’re converting over to AS3.
I’ve been using AS3 for a couple of months now and I’m loving it. Naturally, I found that everything takes longer to build to start with, but the extra power you get from AS3 is worth it and I’m sure that in no time we’ll be knocking out code as quick as we could using AS2.
Looks like I’ll have to keep an even closer eye on your site from now on ;-)
I understand that this is just for people brand new to AS3, but please don’t teach them bad habits from the start:
import flash.display.*;
This is extremely lazy coding. Why are you importing the entire display library? You’re not using SpreadMethod, PixelSnapping, MorphShape or any of the other 30+ libs you just included. You need only one. The same goes for Events and UI.
The example didn’t need to extend MovieClip as Sprite would have been perfectly suitable with less overhead.
Finally please please teach them to properly set the scope of their vars and functions.
I know these things are probably way beyond the idea of this simple tutorial, but I bet lots of people read your blog, so it could make a big difference! :)
Nice and constructive criticism, Rich.
Rich makes some good points - maybe you should fix those issues Emanuele.
On the Sprite vs MovieClip issue - I made the same mistake when I first started coding in AS3. Just to clarify, MovieClip only needs to be used if a timeline is present, otherwise Sprite is fine and less CPU intensive.
Nice one Emanuele.
I guess you should really declare the datatypes of the vars as well. Strict typing will help improve the debugging of you code at compile time.
Keep up the good work.
Adrian
Thanks for doing this, Emanuele
I felt like I was never going to start with AS3, this is just what I needed: an AS3-for-dummies-tut
Thanks a lot!
@Emanuele
Yes I understand that, but what I mean is that is there any other reason why we should change to AS3 then because of the libraries?
Hawdon: I think you can keep using AS2 for at least another 2 years.
Meanwhile, you should wisely learn at least AS3 basics.
Great. But I would love a new tutorial, or atleast continue the AS2 version. I think many people would agree with me. By the way, I saw a picture of you! :D Bye!
@Rich: I thought that even if you import many classes, only the ones you use are exported in the final swf?
This’ll probably make me jump in and start learning AS3, been scared off of it by the harsh differences…
Any chance you could show us more on physics engines? I’ve had a look myself but it’s all Greek to me :S
I’ll be coming back to Flash soon. I finally was able to understand OOP through Java.
@Sunil - it is true that only the used classes are in the final swf, but always take into consideration the readability of your code - the cleaner you keep it, the quicker you can fix things.
If you use a decent IDE like FlashDevelop then it’ll auto-build the import statements for you as soon as you start coding, so you don’t even need to really worry about this!
I’m amazed how many people are scared of AS3 and want to stick with AS2 - AS3 is extremely powerful and SO much faster than AS2! With the Flash9 uptake rate in the high 90%s there’s no good reason to ignore it. I guess old dogs don’t like learning new tricks? :)
I was just wondering, how calling an entire library affect the readability of the code. Basically just saves a lot of time.
Personally I’m just feeling the same things I did when I learned C++ after doing a course in C.
This transition is so much similar.
Yeah AS3 is powerful. I’m doing stuff in both AS3 and AS2, using AS2 for the simpler(less resource consuming) projects while AS3 for some hardcore action.. ;)
I need help, I’m new to AS3 and Flash CS3… So I got this problem, when i click the pencil to edit the class file it shows this error: “A definition for the document class could not be found in the classpath, so one will be automatically generated in the SWF file upon export.”
It’s weird, because I was making it the same way as the tut says… someone?
im stuck
whenever i open up the swf at that i made it doesn’t have the ball shows up, its just and empty movie clip. can anyone tell what to do?
Hrmm… same problemo as Diego. I (assume I) did everything the same as the tutorial. It’s either because I’m doing it on a iMac (tut. is on Windows) OR because I’m not setting up all my properties correctly.
To find out what’s going on with my CS3, please can you be more specific as to these questions?
Should I use “Object Drawing Mode”?
Should I create a separate layer for the code? (On a different tutorial for AS3, a separate Layer 2 for code was created which, btw, worked…)
Can’t think of anything else at this stage. Help would obviously be appreciated.
Jmz
Oh and another thing; Should I use the “Modify” -> “Movie Clip” on the ball I drew on the Stage. No specifics are drawn to that either… yes, I am n00b…
Unfortunately, that’s the only way I learn… everything, absolutely EVERYTHING told to me in a very anal way
OR
I don’t learn… AT ALL :\
Sorry for double post. (Yes, ironic I know)
Great tutorial, just what I was looking for. I simplified a little (I had no need for class) and works realy well. Many thanks.