Thursday 27 March 2008

Creating a platform game in as3

I've always wanted to create a platform game, so here goes. 


In a platform game we have a moving character, several platforms, and some type of vector, such as gravity or wind.

I'm going to create all of the movieclips in actionscript for now, so you won't need to set anything up.

import flash.display.*;
import flash.events.*;
stage.frameRate = 30;
stage.addEventListener(Event.ENTER_FRAME, run);

var gravity:Number = 0.2;
var velocity:Number = 0;
var char:MovieClip = new MovieClip();
char.graphics.lineStyle(2, 0x112233);
char.graphics.beginFill(0x112233);
char.graphics.drawRect(275, 0, 20, 50);
char.graphics.endFill();
addChild(char);

var land:MovieClip = new MovieClip();
land.graphics.lineStyle(2, 0x112233);
land.graphics.beginFill(0x112233);
land.graphics.drawRect(0, 350, 550, 25);
land.graphics.endFill();
addChild(land);

function run(event:Event) {
if (char.hitTestObject(land)) {
velocity = 0;
}
char.y+=velocity;
velocity+=gravity;
}







 Ok you may need to refresh the page to view the swf.
as you can see, the character block falls down with increasing velocity and as it hits the floor it stops.

Lets explain the code so far:-

Lines 1-2: Importing the packages that i will use in my actionscript file
line 3: Setting the framerate to 30, this is how many frames per second go past.
line 4: This is an eventlistener that runs the function run on every frame, so 30 times a second.
lines 5-6: Setting up the variables, gravity will be a constant but velocity will change.
line 7: Setting up a new movieClip called char
line 8: The lineStyle of the char movieClip, 2 pixels thick and a dark blue colour.
line 9: The fill colour of char, same as the line colour
line 10: Creating a shape for the char movieclip, this is a rectangle. drawRect(x, y, width, height)
line 11:Telling flash to end the fill that we started on line 9
line 12: Adding the char movieclip to the stage.
lines 13-19: Setting up the land movieclip, the same way as we created the char movieclip.
line 20: Declaring the function "run" with an event type of event.
lines 21-23: An if statement that says if the char movieClip collides with the land MovieClip than set the velocity to 0.
line 24: Setting up the gravity vector, so that the "char" movieClip's  y axis is affected by velocity.
line 25: Increasing the velocity variable by gravity once per frame. This will make the char fall to the land with increasing speed.

Thats all for this first post on creating a platform game in as3.
The next section will be out shortly.

No comments: