Tuesday, September 27, 2011

AS2: Gravity

Source code available at: http://adf.ly/2vrFM


Welcome to Tutorial #2! In this tutorial, I will show you how to program your characters in your game to respond to gravity. By the end of this tutorial, your character should be able to jump with either the space bar or "W".

Let's get started  by creating a new flash document. Select "AS2" as the programming language.

First off, let's make a movie clip for our character:













Notice how the registration point is at the bottom center square. This is where we want the character to react with the ground.

Next, we need to create the ground movie clip.










After you have created 2 movie clips (character and ground), give the ground an instance name of "ground". You can find this option in the properties panel.








Now you are ready for the code. Enter the following code into the actions of your "character" movie clip:


onClipEvent(load) {
falling=false;
hitting=false;
gravity=10;
speed=6;
jump=0;
jumping=false;
}
onClipEvent(enterFrame) {
if(!_root.ground.hitTest(this._x, this._y, true) && !jumping) {
_y+=gravity;
gravity=10;
falling=true;
}
if(Key.isDown(Key.SPACE) && jumping==false) {
jumping=true;
}
if(jumping) {
this.gotoAndStop("jump")
this._y-=jump;
jump-=1.7;
if(jump<0) {
falling=true;
}
if(jump<-15) {
jump=-15;
}
}
if(_root.ground.hitTest(this._x, this._y, true) && falling) {
jump=12;
jumping=false;
falling=false;
}
}


If you would like to edit the gravity, simply edit the following:
jump-=1.7;
Increasing the number in this variable will make the character jump lower.

If you would like to use the "W" key instead of the Space Bar, change this:
if(Key.isDown(Key.SPACE) && jumping==false) {
To:
if(Key.isDown(87) && jumping==false) {


Well, that concludes today's tutorial on gravity! Feel free to download the source file for this
tutorial: http://adf.ly/2vrFM

1 comment:

  1. Thank for your post, I will give you +1 for your blog, Please take a look in Develop Alone

    ReplyDelete