sábado, 9 de abril de 2011

[ActionScript 2.0] making your character jump

Making your character jump when programming a game in Action Script 2.0 might sound like an easy task, yet I found it really tricky and decided to post the procedure here. I will be assuming that you are familiar to Adobe Flash in any of its versions, but not expert enouhg to get your character jumping. (maybe I'll make a detailed Flash game programming tutorial someday)

All rigth first of all we need our character designed, go and draw something nice, and convert it to movie clip and then press F9 to edit its actions.

first of all we need some variables set, in the load event.
onClipEvent (load) {
 var isJumping = false;
 var hgt = 0;
}
isJumping will tell us wherever the character is jumping or not.
hgt will tell us what I like to call jump-units (different to height. you will se why).

now lets say we want it to jump when the UP key is pressed, so we need to add the keyboard listener in the enterFrame event to get a smooth movement.

all right we code:


onClipEvent (enterFrame) {
 if (Key.isDown(Key.UP)) {
  //this only in case you got some frames within the character
  //special to reproduce when jumping.
  this.gotoAndStop("jump_frame");
  //now we set the jumping variable to true
  //because we are jumping :D
  jumping = true;
 }
 if (jumping) {
  //now we catch that it is performing a jump
  //and increase the jump-units variable by 1
  hgt++;
  //now let's say the jump capacity is three-jump-units
  //this means that max height will be 3*40, because in this case
  //I'm setting 40 height-units for every 3 jump-units
  //you can set any variables you like here, maybe if your game
  //has upgrades
  if (hgt<3 hgt="">0) {
   //this means our character is going up
   this._y -= 40;
  }
  //now the max height is reached, we want it to go down 
  //the same jump-units it went up this means 3*2 = 6
  //so when our jump-unit counter reach 6 means that our
  //character is in the floor (you can also set the floor
  //to a variable) and we should stop doing jumping stuff
  if (hgt>3 && hgt<6 br="">   this._y += 40;
  }
  //here we get hgt == 6 so floor is reached and we 
  //need to reset all variables and do stop-jumping stuff 
  if (hgt == 6) {
   //reset the jump-units, ready for the next jump 
   hgt = 0;
   this.gotoAndStop("normal_position");
   //we are not jumping any more 
   jumping = false;
  }
 }
}


This looks like a huge method!! but actually there are a few lines of code, but I wanted to make sure it was well explained. so Adding this code to your character hopefully will get it to jump. If you combine this with other keys, you will get the movement job done and start focusing in creating a great game :D


Happy Coding!

No hay comentarios:

Publicar un comentario