Tuesday, July 15, 2014

Jumping in as3

Jumping is a mechanic present in many video games. However, it takes some knowledge in physics to understand how it works. When an object jumps, it begins with maximum velocity moving away from the ground. the velocity decreases until the the object stops (reaches 0 velocity) and begins to fall faster and faster (begins negatives velocity).

Let's take a look at how to implement this jumping mechanic in as3:

//add the listener that allows the object we need to jump //(jumpingObject) to move on enter frame
//note: jumpingObject is a moving
jumpingObject.addEventListener(Event.ENTER_FRAME, jumpFunction);
//jumpSpeed variable that begins the velocity at its maximum value
var jumpSpeed:Number = 10;

//function for jumping
function jumpFunction(event:Event) {
     if(jumpSpeed >= -10) {
          //move the object up (then down) at a changing rate by decreasing the jumpSpeed
          jumpingObject.y = jumpingObject.y - jumpSpeed;
          jumpSpeed --;
     else {
          //reset the jumpSpeed for the next jump
          jumpSpeed = 10;

Take a look at what this produces:

Here's the FLA link if you want to look at it on your computer: .fla

In other news, Lamb in a Pram Lite will be coming out soon. Thanks for reading!

No comments: