Tutorial: Create a Platform Game in AS3


Written By MrSun at 8:00 am - Saturday, August 30th, 2008
Categories: Flash

Step 1: Basic Character Programming

Well, here we are in our first advanced tutorial. This time we’ll be creating a platform game similar to my GlowSticks except in ActionScript 3 and coded better. Let’s begin, shall we?

Let’s first begin with the basic setup of our game. I’m going to make the background black and the frame rate 24 fps (like in previous tutorials). The first thing to make is our little character. I won’t be too artistic with this one, just a little white circle
My character guy
Its dimensions are 25×25 pixels.

Next, convert it into a MovieClip and give it an instance name of mcMain. Now, we can add code to move this character.

Just create a new “actions” layer and place this code in the first frame:

//These variables will note which keys are down
//We don't need the up or down key just yet
//but we will later
var leftKeyDown:Boolean = false;
var upKeyDown:Boolean = false;
var rightKeyDown:Boolean = false;
var downKeyDown:Boolean = false;
//the main character's speed
var mainSpeed:Number = 7;

//adding a listener to mcMain which will make it move 
//based on the key strokes that are down
mcMain.addEventListener(Event.ENTER_FRAME, moveChar);
function moveChar(event:Event):void{
	//if certain keys are down then move the character
	if(leftKeyDown){
		mcMain.x -= mainSpeed;
	}
	if(rightKeyDown){
		mcMain.x += mainSpeed;
	}
	if(upKeyDown || mainJumping){
		mainJump();
	}
}

//listening for the keystrokes
//this listener will listen for down keystrokes
stage.addEventListener(KeyboardEvent.KEY_DOWN, checkKeysDown);
function checkKeysDown(event:KeyboardEvent):void{
	//making the booleans true based on the keycode
	//WASD Keys or arrow keys
	if(event.keyCode == 37 || event.keyCode == 65){
		leftKeyDown = true;
	}
	if(event.keyCode == 38 || event.keyCode == 87){
		upKeyDown = true;
	}
	if(event.keyCode == 39 || event.keyCode == 68){
		rightKeyDown = true;
	}
	if(event.keyCode == 40 || event.keyCode == 83){
		downKeyDown = true;
	}
}
//this listener will listen for keys being released
stage.addEventListener(KeyboardEvent.KEY_UP, checkKeysUp);
function checkKeysUp(event:KeyboardEvent):void{
	//making the booleans false based on the keycode
	if(event.keyCode == 37 || event.keyCode == 65){
		leftKeyDown = false;
	}
	if(event.keyCode == 38 || event.keyCode == 87){
		upKeyDown = false;
	}
	if(event.keyCode == 39 || event.keyCode == 68){
		rightKeyDown = false;
	}
	if(event.keyCode == 40 || event.keyCode == 83){
		downKeyDown = false;
	}
}

This code will simply make the character move left and right. Now, we have to make the character jump. We’ll accomplish this with a jump function and running it whenever the up key is down. First, we have to define a few variables:

//whether or not the main guy is jumping
var mainJumping:Boolean = false;
//how quickly should the jump start off
var jumpSpeedLimit:int = 15;
//the current speed of the jump;
var jumpSpeed:Number = jumpSpeedLimit;

Then, we’ll define a function which will make the guy jump. It’ll take some complicated math.

//jumping function
function mainJump():void{
	//if main isn't already jumping
	if(!mainJumping){
		//then start jumping
		mainJumping = true;
		jumpSpeed = jumpSpeedLimit*-1;
		mcMain.y += jumpSpeed;
	} else {
		//then continue jumping if already in the air
		//crazy math that I won't explain
		if(jumpSpeed < 0){
			jumpSpeed *= 1 - jumpSpeedLimit/75;
			if(jumpSpeed > -jumpSpeedLimit/5){
				jumpSpeed *= -1;
			}
		}
		if(jumpSpeed > 0 && jumpSpeed <= jumpSpeedLimit){
			jumpSpeed *= 1 + jumpSpeedLimit/50;
		}
		mcMain.y += jumpSpeed;
		//if main hits the floor, then stop jumping
		//of course, we'll change this once we create the level
		if(mcMain.y >= stage.stageHeight - mcMain.height){
			mainJumping = false;
			mcMain.y = stage.stageHeight - mcMain.height;
		}
	}
}

That’s some pretty intense code, eh? And you would have never thought that making a simple platform game would be so intense, right? Well, there’s a reason why this tutorial is labeled “Advanced”.

But now, it is time to close up this part of the tutorial. Next time, we’ll create a level with blocks we can walk on!

Final Product

Source .fla File

49 Comments

ryan:

I have a question, does the character have to be a little circle? or can we make it different?


Bruce:

I LOVE this tutorial and very much appreciate it man. However when i tried to replicate this page, my character would simply not jump!
I copied and pasted all of the code EXACTLY from this page and it still didn’t work. I simply gave up and downloaded the source file and copied the actionscript over to my file and it worked fine then. I can only assume that the code on this page has an error on it somewhere?


Peter:

HI,
This missing from the movement key detection:
if(upKeyDown || mainJumping){
mainJump();
}
Put that in and he’ll jump.


Kyle:

I was wondering will it work with AS2??? I really need to know before i even attempt this tutorial


mckendorh:

hi how can i make it work in AS2


Dave:

Can you please try and explain that crazy math plaease? It works great but I wanna know exactly how it works.
Thanks


gamestube:

Thank boy! this is great tutorial! thank!


Masuma!:

hey i would like to ask a favour of you, could you PLEASE PLEASE PLEASE make a tutorial just like this but for Action Script 2.0 i would really appreciate it =)


sticmakerman:

exactly where in the actions layer do i have to place the second and the third codes?


Hot Rod:

All of the code can go on the same frame. One section copy and pasted one right under the other.

Just be sure to add in the jumping check that Peter mentioned in an above post to allow the ball to jump


coder:

i pasted all the code in as3 it all works but the jumping action where do i put?

if(upKeyDown || mainJumping){
mainJump();
}


P282:

THIS WILL NOT WORK WITH ACTION SCRIPT 2, (AS2) if you want one for (AS2) then go google it or go to flashkit.com, otherwise this will not work for (AS2) this is only for the new Action script 3 (AS3) winch can be found in Flash CS3 and Flash CS4.


FRK:

YES!!! thank you very much for this tutorial. REAL NICE!!!!!


SG2:

Thank you very much for creating this tutorial. This was infinitely useful in my final project for my flash class, given how few AS3 tutorials there are available on the net these days. 🙂

PS – sent you an e-mail with some additional questions.

–SG2


Some guy:

Every time I get it to put in the first code it says
**Error** Scene=Scene 1, layer=actions, frame=1:Line 14: The class ‘Event’ could not be loaded.
function moveChar(event:Event):void{

**Error** Scene=Scene 1, layer=actions, frame=1:Line 30: The class ‘KeyboardEvent’ could not be loaded.
function checkKeysDown(event:KeyboardEvent):void{

**Error** Scene=Scene 1, layer=actions, frame=1:Line 48: The class ‘KeyboardEvent’ could not be loaded.
function checkKeysUp(event:KeyboardEvent):void{

Total ActionScript Errors: 3 Reported Errors: 3

If you have any suggestions, please tell me.


Me:

Thx for the guide!
Even tho i didnt understand a thing :S
Gonna read it more throughly! 😀
And btw Some guy, are you using actionscript 2???


lvman:

hey, thanks real helpful. i was wondering what can be done to make it jump higher?


simon:

@Dave – The math is really not that crazy. No more than a little arithmetic. Go through it calculating jumpSpeed frame by frame. Heck, you could even graph it 🙂 That way you’ll really understand what’s going on (much better than if someone just told you).


Gardengnomes:

okay.. i got an error it says: 1120: Access of undefined property mainJumping. and: 1180: Call to a possibly undefined method mainJump.


jan:

can i know how to make the main remain the same position?i mean,i’ve placed the main slightly higher than urs,then when i jump,it falls on the floor.


mctoast:

this doesnt work D: does it can be used on flash 8? and what actions need to be inside the balloon and whats in layer?!?!?!?! plz someone help me D: heres my email. gangstarapper_94@hotmail.com i wish some one seriusly help me whit this.


mcdurk:

yea i did everything and followed every step and read all the details and it just wont work 🙁
it keeps giving me like 30 errors on undefined properties and stuff.
i need help seriously!!!


Bilbo:

The first block of code doesn’t work on its own because the jump variable and function aren’t identified yet. Also, for the jumping math, I just use jumpSpeed += 1, and it looks fine.
For those who ask where to put code etc., I suggest learning your basics before tackling something this advanced. 😛


Loon:

Thanks, after about 42 tries this is the tutorial that finally taught me wtf actionscript is all about.


Yewhral:

Great tutorial. Finally someone explained and commented the code for as3.
But my guy after first jump is higher than at the beginning. Why?


Yewhral:

Do the hero have to have same height as width?


nmc:

the code does not wofrk for me


b01ina:

i found this site by chance, which is great but i dont understand why the jumping isnt workin. i really need this game done by early november. if any one can help me with the jumping i will gladly appreciate it my email is: b01ina_j01y@live.com.au

my msn is: my_car_rules@hotmail.com

dont get these mixed up as i dont check my msn because of the amount of spam i get.

thanks


Martin:

Hi,

thanks very much for your great tutorials. They are brilliant!

I have one problem with AS3 in this lesson above.

I modified your AS3 script and I added a motion hero. Almost everything is OK. He jumps correctly, but when he walks his legs don’t move.

What’s going on? Where the problem is?

I’m pasting a part of the code, which is connected to this problem, I suppose:

hero.addEventListener(Event.ENTER_FRAME, moveChar);
function moveChar(event:Event):void{
//if certain keys are down then move the character
if(leftKeyDown){
hero.x -= mainSpeed;
hero.scaleX=1;
hero.gotoAndStop(‘walking’);
}
else if(rightKeyDown){
hero.x += mainSpeed;
hero.scaleX=-1;
hero.gotoAndStop(‘walking’);
}
if(upKeyDown || mainJumping){
mainJump();
hero.gotoAndStop(‘jumping’);
}
else {
hero.gotoAndStop(‘still’);

}
}

Thank in advance,
Marcin


Spoki:

Thank you 😀


Святослав Родионов:

Познавательно, а продолжение будет?


Alex:

hi, how can we put more than one enemy in?


longhoanggiang:

thanks so much, as2 -> get out


nirbhay:

hey very helpful tutorial. thanks.
hey you could modify it to use gravity instead of hardcoded values, it may be easier to understand that way.


OMGWTFBBQFML:

Its so ridiculous how many people think this is for AS2 … if you read the top sentence, it has a link to something similar for AS2.


Mac:

code is not working
I copied and pasted all code one after another n got lots of errors

1119: Access of possibly undefined property x through a reference with static type Class.


lemonslice:

Sweet man… thanks alot you deserve a medal for it!! hehe.
I dunno what the ppl are crying about it works 100% perfect


carrie:

may i noe how to change the character n everything wif my own design???
i try many times wif diff method…but i cant get it…can u pls help me…


Christo:

Make it work in AS2? WTF! Learn AS3 already you dinosaurs! x|


cohen:

hey i cant get the guy to move because the speed and jump actions dont have a defined property. how to define how much they should jump or move by?


Leo:

Hi, very good tutorial, but I don’t know how to change the jump max height…


at war with AS3:

got everything in place but i keep getting compiler error 1083: Syntax error on line 77. } else { is unexpected. i’m pretty sure i told them it was coming…


Josh:

ok so what if we want a character who looks different when they move left or right? I find that many tutorials teaching how to make a platformer just ignore this and do the simple object thing.


tofu:

AHHHHH!!!
Ní thuigim… 🙁


NoviceCoderJ:

Hey there, Novice AS3 coder here, and I have no problems so far, but what I am doing here is reading the code to understand why it was written that way, and its all good to my eyes except for the keyCode, I was wondering why you use what appear to be a random selection of numbers to identify keys. Are there KeyCodes for every key on the keyboard, if so how do I obtain a copy if not, please explain why you use keyCodes?


Laatste nieuws « Weblog:

[…] is het Mario-spelletje geüpload. Om het spelletje te maken heb ik gebruik gemaakt van de tutorial: . Maar genoeg over het spelletje. We gaan terug verder werken aan onze […]


Mariannen:

wow, one year later… and there comes my question 😛
thank you for this tutorial, finaly i am getting to undersand AS3 😛
I want to make some kind of platform game, but with video images. So the problem i have now, is that it has different images for each key. Therefor i used this:

mcMain.addEventListener(Event.ENTER_FRAME, moveChar);
function moveChar(event:Event):void {
//if certain keys are down then move the character
if (leftKeyDown) {
mcMain.x-=mainSpeed;
mcMain.scaleX=-1;
mcMain.gotoAndStop(‘run’);
}
else if (rightKeyDown) {
mcMain.x+=mainSpeed;
mcMain.scaleX=1;
mcMain.gotoAndStop(‘run’);
}
else if (upKeyDown||mainJumping) {
mainJump();
mcMain.gotoAndStop(‘jump’);
}
else {
mcMain.gotoAndStop(‘stand’);
}

}

but when i use the keys i can not use jump and run at the same time. And i can run in the air 😛 can you please help me with this problem?

tnx


Platform games « Brecht cosyns's Webanimatie:

[…] trytutorial now! […]


Cameron:

For some reason my character does not land at the base of the screen after jumping, even if starting at the y=0 he seems to stop around y=5 or so. My code is identical to yours. After the first jump, the character lands roughly around y=5 and jumps from that reference and lands there after that.


«
»