AS3: Avoider game, part 12, and a new project
The latest post at MichaelJWilliams' blog brings his AS3 Avoiding game tutorial to an end with part 12 ...or does it?
This final segment details garbage collection, the nitty gritty part of game development that's important to you, but doesn't bother the players that much, until they notice the lag that inevitably comes from leaving each of those enemies onstage...
Anywho, it's a must-read and a nice tie-up-the-loose ends post, and this series of tutorials is once of the best out there.
Now, why may it not be coming to an end?
Myself and Michael shall shortly be launching a new site geared around the wonderful Avoiding game, hosting both our tutorials amongst other things, and we'd love for you to get involved! Perhaps you have an avoiding game you've written and want to show it off, or you want to share the secrets to that interesting feature you've worked in, throw us an email or hit me up in the comments for this post and we'll get back to you. Stay tuned for more information :)
AS3: Avoiding Game Tutorial, pt.11
Here we go, another interesting instalment in MichaelJWilliams' AS3 Avoiding game tutorial, part 11, covers saving and loading shared objects in AS3. Handy for keeping highscores, level progress and stats. Make sure you check it out!
AS3: Button Mashing Game
You may or may not recall, a long time ago, I wrote a tutorial on how you could create a button mashing game in AS2. (Yes, I also promised more parts to it and didn't deliver, eep!) And a little while ago, someone commented asking for an AS3 conversion.
Now, I'm still not confident enough with AS3 to go writing game engine tutorials with it, so I leapt over to the forum and asked if anyone there would take on the challenge.
Luckily for me, HiddenSpartan did, and has very nicely allowed me to post it up here on the blog.
You can grab the source at HiddenSpartan's DeviantART page, here, or download it from FH, here. Remember to give credit if you use it!
8-Way movement in AS3
Now, you'll have to bear with me on this one, (I'm still learning AS3 too) but I may well have an AS3 tutorial for you today!
Let's learn how to listen for keys, and how to react to keyboard input. In this example, how to move a player when the user hits the cursor/WASD keys. (Which I have shown you before in AS2)
I'll be putting all of this code on the frame (Sorry strict AS3 writers, but for now, it's frame coding for me!), I will however place the character from the library, leaving nothing on the stage.
Setting up the stage and character
After quickly setting up your stage (I have mine on 24fps, 550 by 400px, you can have yours however you like so long as it's an Actionscript 3 document), you'll need to draw your character. For the purposes of this tutorial I've drawn a face, but let's face it, I'm no artist. So I'm sure you can think of something more imaginative :)
Once you've drawn your character, you need to convert it to a movie clip and give it an appropriate name (Anything will do), then you can delete it from the stage. Don't worry, it's not gone. Hit CTRL+L to bring up your library (if it isn't already open) and you'll see it right there at the top.
Right click your object and hit linkage, changing the class to 'char' as shown above. This will let us reference it in our code.
Getting your character onstage
That's all the setup we need to do, so lets move onto the code shall we? Click on the first frame in your timeline, and hit F9 to open the actions panel if it's not open already. This is where we will be coding the entireity of your character's movement.
The first thing we're going to do is to bring our player onto the stage from the library, and set it's position onstage. Remember how we gave it a class 'char'? Well now's the time to use it.
-
var myChar:char = new char();
-
myChar.x = 275;
-
myChar.y = 200;
-
addChild(myChar);
Basically, what we're doing here is creating a new instance of our 'char' object, and giving it the name myChar. We then set it's x and y coordinates (Note that AS3 does not use _x,_y as AS2 did) before finally adding it to the stage with addChild. Go ahead and test your movie, see if everything's working as it should be.
Looks like it's going fine to me! We'd better get our character moving eh?
Keylisteners and keyCodes
Now, unlike AS2, AS3 does not have a built in function for checking if a key is down. Instead, it checks for when a key is pressed, and when it is released. To do this, we're going to have to use a special type of Event Listener, called a Key Listener. Two infact!
-
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownFunction);
-
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpFunction);
These are our Keylisteners. The top one waits until a key is pressed, and then runs a function, in this case (imaginatively) called 'keyDownFunction'. And yep, you guessed it, the bottom one waits for a key to be released and then runs 'keyUpFunction'. Now, maybe we'd better write those functions eh?
The two functions are alike, in that both will check the key pressed/released and then set a boolean for movement accordingly. (A Boolean being a variable that is either true, or false.) We'll know that your character should be moving if the corresponding key has been pressed, but not yet released, so that's what we'll check for.
First things first, we need to define our Boolean variables at the top of the code, and initially set them to false.
-
var moveLeft,moveRight,moveUp,moveDown:Boolean = false;
That should do the trick! Now down to the function...
To define our function, we need this first line:
-
function keyDownFunction(event:KeyboardEvent) {
This includes the function identifier (keyDownFunction) which we use to call it when it's needed.
Next, I've included this line. Not nessicarily needed for the game, it will send the corresponding keycode for the key you've pressed to the output panel. This comes in handy when working out what keyCodes you need to check for.
-
trace("Key Pressed: "+(event.keyCode));
Traces make no difference to the final .swf file, but can be extremely helpful when debugging code! You can omitt this line if you wish to.
Now we get to the meat of the function, the iftests that check against the key you pressed, and act accordingly.
-
if (event.keyCode==37||event.keyCode==65) {
-
moveLeft=true;
-
}
-
if (event.keyCode==39||event.keyCode==68) {
-
moveRight=true;
-
}
-
if (event.keyCode==38||event.keyCode==87) {
-
moveUp=true;
-
}
-
if (event.keyCode==40||event.keyCode==83) {
-
moveDown=true;
-
}
You'll see that in AS3 I have referenced the actual keyCodes of the keys, rather than naming the cursor keys Key.LEFT/Key.RIGHT etc. I think AS3 enforces this, anyone who knows differently do leave a comment won't you? Memorising keyCodes isn't my forté, hence the trace line. Another notable difference from this to AS2 is that you can no longer use the AND or OR keywords in if statements, instead having to use && or || respectively.
The keyCodes here are those for WASD and the Cursor keys.
37 & 65 - Left Cursor & A
39 & 68 - Right Cursor & D
38 & 87 - Up Cursor & W
40 & 83 - Down cursor and S
The function will set the corresponding Boolean variable to true when the key is pressed.
Now for the function that's carried out when a key is released:
-
function keyUpFunction(event:KeyboardEvent) {
-
if (event.keyCode==37||event.keyCode==65) {
-
moveLeft=false;
-
}
-
if (event.keyCode==39||event.keyCode==68) {
-
moveRight=false;
-
}
-
if (event.keyCode==38||event.keyCode==87) {
-
moveUp=false;
-
}
-
if (event.keyCode==40||event.keyCode==83) {
-
moveDown=false;
-
}
-
}
Pretty similar to the firs one, the only difference being that it sets the Boolean to false when the right key is released.
Let's get it moving then, eh?
Because this is a tutorial, and it's here to teach you something (I hope!) then I'll introduce the AS3 enterFrame listener here too, and control the player movement from a function. Which we'll write now.
-
function moveChar() {
-
if (moveLeft) {
-
myChar.x-=speed;
-
}
-
if (moveRight) {
-
myChar.x+=speed;
-
}
-
if (moveUp) {
-
myChar.y-=speed;
-
}
-
if (moveDown) {
-
myChar.y+=speed;
-
}
-
}
This function is pretty self explanatory. If the boolean is true, it'll move the character in the correct direction by 'speed', which is a variable we should define at the start of the file.
-
var speed:Number = 5;
There. All done right? Nope! We need to make sure this function runs every frame! So it's back to those Event Listeners again.
-
addEventListener(Event.ENTER_FRAME, enterFrameFunc);
This listener will run the function identified as 'enterFrameFunc', every frame. Simple enough, so we'll just go and write that function to finish off our code:
-
function enterFrameFunc(event:Event) {
-
moveChar();
-
}
Now you can test your movie and move your character with the WASD/Cursor keys, Huzzahs and Hurrahs!
And I'll just paste the entire script for you copy-pasters... (You'll learn nothing, nothing!)
-
addEventListener(Event.ENTER_FRAME, enterFrameFunc);
-
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownFunction);
-
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpFunction);
-
-
var moveLeft,moveRight,moveUp,moveDown:Boolean = false;
-
var speed:Number = 5;
-
-
var myChar:char = new char();
-
myChar.x = 275;
-
myChar.y = 200;
-
addChild(myChar);
-
-
function keyDownFunction(event:KeyboardEvent) {
-
trace("Key Pressed: "+(event.keyCode));
-
if (event.keyCode==37||event.keyCode==65) {
-
moveLeft=true;
-
}
-
if (event.keyCode==39||event.keyCode==68) {
-
moveRight=true;
-
}
-
if (event.keyCode==38||event.keyCode==87) {
-
moveUp=true;
-
}
-
if (event.keyCode==40||event.keyCode==83) {
-
moveDown=true;
-
}
-
}
-
function keyUpFunction(event:KeyboardEvent) {
-
if (event.keyCode==37||event.keyCode==65) {
-
moveLeft=false;
-
}
-
if (event.keyCode==39||event.keyCode==68) {
-
moveRight=false;
-
}
-
if (event.keyCode==38||event.keyCode==87) {
-
moveUp=false;
-
}
-
if (event.keyCode==40||event.keyCode==83) {
-
moveDown=false;
-
}
-
}
-
-
function moveChar() {
-
if (moveLeft) {
-
myChar.x-=speed;
-
}
-
if (moveRight) {
-
myChar.x+=speed;
-
}
-
if (moveUp) {
-
myChar.y-=speed;
-
}
-
if (moveDown) {
-
myChar.y+=speed;
-
}
-
}
-
-
function enterFrameFunc(event:Event) {
-
moveChar();
-
}
So, that concludes this tutorial! You can grab the source .fla here, 'cause we're good like that. Please remember, this is as much a learning experience for me as it is for you, if you can see anywhere I've done something wrong, or in an odd way, or if you can improve upon it in any way, please feel free to! Comment below or hit the forums with any questions or comments you may have, and I hope this helps!
AS3: Avoiding game tutorial parts 8, 9 and 10
Ok, so last time remember how I said I couldn't blog about these fast enough?
I wasn't lying :P
MichaelJWilliams has been rather busy with his continuation in AS3 of our Avoiding game tutorial, and since my last post has released parts 8, 9 and 10! Covering Preloaders, Music, Sound Effects and Multiple Levels, these installments are a valued addition, and you should definitely go check them out!
AS3: Avoiding game tutorial pt.7
It seems MichaelJWilliams is releasing these tutorials faster than I can blog about them now!
Part 7 of Michael's translation of our AS2 Avoiding game tutorial series has now been released over on his blog, and as per usual, I highly recommend it! In this installment, Michael talks you through adding Keyboard control to your player.
(Note: It's not really a translation anymore, he's overtaken us in features now!)
Meanwhile, I'll hijack the bottom of this post to remind any readers who aren't aware, we do have a forum, where help and feedback can be gotten quicker than in comments, or email, and from a wider range of developers. So I suggest you go and check it out!
AS3 Avoider: Updates and Part 5
Hey everyone, you remember Michael James Williams? Writer of the AS3 version of our very own Avoiding Game Tutorial? He's back and he's blogging!
After taking time out of blogging to complete some contract work, Michael's writing once more and his first action has been to rewrite sections of the AS3 Avoiding Game tutorial (Parts 1, 2, 3 and 4) to increase efficiancy and reusability of code, and I fully advise you to check them out again. Michael says they'll be quicker to follow the second time round ;)
Also, he has released Part 5 of the AS3 Avodiing Game tutorial, which introduces Score, a Clock and will explain the concept of class inheritance to you. I know I'll be following it after checking through the first four parts again!
AS3 preloader tutorial
Preloader Tutorial
Hello and welcome to..
THE ULTIMATE AS3 PRELOADER TUTORIAL
sorry, I couldn't help myself, but now without further delay, here it is!!
1. The .FLA
First we create a new Actionscript 3 flash file. Then change the dimensions to the dimensions of your game/movie.
Then we'll have to link an actionscript file to our .fla so either type "Preloader" in the class textbox on your current screen
or goto "File->Publish Settings->Flash" and then look for a Settings button next to the dropdown box where you choose your script version.
and then set te Document class to "Preloader".
OK, our .fla is done and set up for the job.
2. The .as
This is the most important step in the creation of our preloader now we will make the actionscript to go with our .fla.
First I'll post all the code and then I'll explain it step by step.
package{
import flash.display.Sprite;
import flash.display.Loader;
import flash.events.Event;
import flash.events.ProgressEvent;
import flash.net.URLRequest;
public class Preloader extends Sprite{
var request:URLRequest = new URLRequest("site.swf");
var loadbar:Sprite = new Sprite();
var rect:Sprite = new Sprite();
var loader:Loader = new Loader();
public function Preloader():void{
loadbar.x = 175;
loadbar.y = 190;
addChild(loadbar);
rect.x = 1;
rect.y = 1;
loadbar.addChild(rect);
loadbar.graphics.lineStyle(2,0xffffff);
loadbar.graphics.drawRect(0,0,200,20);
rect.graphics.beginFill(0xffffff);
rect.graphics.drawRect(0,0,198,18);
rect.graphics.endFill();
loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, loadProgress);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete);
loader.load(request);
addChild(loader);
}
private function loadProgress(event:ProgressEvent):void{
var percentLoaded:Number = event.bytesLoaded/event.bytesTotal;
rect.scaleX = percentLoaded;
}
private function loadComplete(event:Event):void{
removeChild(loadbar);
}
}
}
This might be a bit overwhelming at the time but don't worry, when you're done with the tutorial you're going to laugh in the face of AS3, Mwahaha!
package{
Every .as file starts with "package{ " wich contains the code of our .as file.
import flash.display.Sprite; import flash.display.Loader; import flash.events.Event; import flash.events.ProgressEvent; import flash.net.URLRequest;
then comes a declaration of all the files we have to include.
public class Preloader extends Sprite{
This is the declaration of our class it will hold all the functions and variables, as you can see it extends a Sprite since our loadbar is going to be a sprite.
var request:URLRequest = new URLRequest("main.swf");
var loadbar:Sprite = new Sprite();
var rect:Sprite = new Sprite();
var loader:Loader = new Loader();
here we declare some variables. a new URLRequest wich will hold the request to our main game/movie, two Sprites one for the entire loadbar and one that will hold the filling of our loadbar, and last but certainly not least a Loader that will load the requested game/movie from the urlrequest.
public function Preloader():void{
This is the initialize function wich will be executed on the loading of our .fla file.
loadbar.x = 175; loadbar.y = 190; addChild(loadbar);
Here we set the location of our loadbar Sprite to the center of the stage minus the half of it's width so that is will be perfectly centered in the middle of our screen. The last line add the Sprite to the stage.
loadbar.addChild(rect);
here we add the Sprite to the stage but this time inside the loadbar Sprite.
loadbar.graphics.lineStyle(2,0xffffff); loadbar.graphics.drawRect(0,0,200,20);
Here we draw the outline of our loadbar using actionscript. the first line set the style of the line to a thickness of 2 and the color black.
the second line draws a rectangle with no filling from the point (0,0) to the point (200,20) inside the loadbar Sprite.
rect.graphics.beginFill(0xffffff); rect.graphics.drawRect(0,0,200,20); rect.graphics.endFill();
This is where we draw the filling of our loadbar. The first line sets the color of our filling to black. the second line draws a rectangle inside our rect Sprite wich is located inside our loadbar Sprite, so the location of our rectangle is loadbar.rect. the last line ends our fill.
loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, loadProgress); loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete);
This adds some eventlisteners to our loading progress. the first is to track how many bytes have been loaded and the second is to track when the loading is complete.
loader.load(request); addChild(loader);
These lines will load the main game/movie and add it to the stage.
private function loadProgress(event:ProgressEvent):void{
var percentLoaded:Number = event.bytesLoaded/event.bytesTotal;
rect.scaleX = percentLoaded;
}
here we declare the function that is used to track the loading progress and handle accordingly.
it calculates a percentage based on the amount of bytes loaded and the total bytes being loaded, the percentage will be a number between 0 and 1.
then it sets the width of our filling to the right percentage.
private function loadComplete(event:Event):void{
removeChild(loadbar);
}
this function will be called by our eventlistener when the loading of our game/movie is done, it will remove the loading bar so the only thing visible will be our main game/movie. you can also add additional code to accompany the completion here like a trace telling that the loading is done.
This is all! Now go test your movie using a nice big main game/movie and if you run into any trouble, just post the problem here and I'll be happy to help you sort things out.
My experiences with AS3: Following the AS3 Avoider tutorial
Well, I followed this a while ago and right now I'm sat in a room with Daryl and co, with a PC, and nothing to do. So here we are , time to write up another experience!
So far I've only reached the end of part 1 of Michael James Williams's translation of our Avoiding game tutorial, and this is what I have so far:
(Yes it's supposed to stop like that :P)
Michael's writing style is excellent for beginners and old hands alike, following the tutorial I didn't feel patronised, even when the tutorial was explaining sections I already understood from my experience in other languages. I would most definitely reccomend following this tutorial to any beginner to AS3, as I came out of it with far more knowledge of the language than when I started.
I shall be following the other tutorials in the series, and I shall report back with my creation then. In the meantime I look forward to more posts from Michael J Williams!
AS3: Basic button and variable intro
Here it is....
My first ever actionscript 3.0 tutorial!
Now it's not going to be a simple: trace("Hello world");
.....Cause that's the same in actionscript 2.
We are going to make a button, which makes a text box display hello world in it, that way the user can see it in the actual finnished file, rather then in our output box only.
This is a very basic tutorial, and even though expirienced AS2 programmers would find this insultingly easy this IS the starting point you have to take. This tutorial is not intended for anybody allready fluent in actionscript 3.0, for more advanced tutorials, go see brarts actionscript tutorials, particually his RTS game.
So a few things you should know when making the jump from actionscript 2:
- Actions only permitted on frames
- Actions must be imported (flash.events.MouseEvent)
- If a script contains no errors from the checking tool, compiler errors can still occur when testing, disabling all script, until it has been fixed.
Now you are aware of what's in store for you we can now start.
So open up flash CS3, CS4, or whatever it is you are using (if you are in the future and as3 hasn't become obselte like as2 has).
Not that we need to, let's put a stop(); function on the frame, just in case we want to add to it later. This is the same as AS2. Now let's import the mouse event functions. The code for this is:
import flash.events.MouseEvent;
Now add a Dynamic text box and give it an instance name of txtvar.
Now with buttons, we only had to worry about instance names IF we wanted to reference them from a frame/as file or move them. But now it is important, so create 2 buttons, and give them instance names of txtbutton and txtbutton2.
Now let's code it all:
Right, we can't use a simple on(release/click/rolover){ or any of that. We need to add an Event Listener, this basicly looks for a specific event the runs a function when the events happens.
So for our first button we will write:
txtbutton.addEventListener(MouseEvent.CLICK,showhelloworld);
So this code is waiting for the mouse to be clicked on the button txtbutton, then when it run the functio we are going to define as showhelloworld.
Now quickly add the other one:
txtbutton2.addEventListener(MouseEvent.CLICK,hidehelloworld);
Now we have listeners to run our 2 functions, and if we checked for errors there wouldn't be any script errors. However your movie would produce compile errors as your script is being told to run a funtion which is undefined. Now lets define them.
With AS3 variables aren't as straight-forward as they are in AS2. Each variable has to be assigned a variable type as you will see here:
function showhelloworld(event:MouseEvent):void {
txtvar.text =("Hello world!");
}
I don't understand what the :void actually does, but I'm sure someone will comment and help us all out :P
So moving on:
function hidehelloworld(event:MouseEvent):void {
txtvar.text =("");
}
And we're done, I think.
DOWNLOAD SOURCE FILE FOR THIS TUTORIAL
Tutorial by Dazza_13
![[del.icio.us]](http://frozenhaddock.co.uk/wp-content/plugins/bookmarkify/delicious.png)
![[Digg]](http://frozenhaddock.co.uk/wp-content/plugins/bookmarkify/digg.png)
![[Google]](http://frozenhaddock.co.uk/wp-content/plugins/bookmarkify/google.png)
![[LinkedIn]](http://frozenhaddock.co.uk/wp-content/plugins/bookmarkify/linkedin.png)
![[StumbleUpon]](http://frozenhaddock.co.uk/wp-content/plugins/bookmarkify/stumbleupon.png)
![[Windows Live]](http://frozenhaddock.co.uk/wp-content/plugins/bookmarkify/windowslive.png)
![[Yahoo!]](http://frozenhaddock.co.uk/wp-content/plugins/bookmarkify/yahoo.png)
![[Email]](http://frozenhaddock.co.uk/wp-content/plugins/bookmarkify/email.png)




