Otto Lives!

We need to modify the frame we named as init to load our Otto movieclip and place him somewhere on the screen:

var mcTrampoline:MovieClip;

var mcOtto:MovieClip;
var dY:Number, dX:Number;
var gravity:Number;

mcTrampoline = _root.attachMovie("trampoline_mc", "mcTrampoline", 1);
mcTrampoline._x = Stage.width / 2;
mcTrampoline._y = Stage.height - 40;


mcOtto = _root.attachMovie("otto_mc", "mcOtto", 2);
mcOtto._x = 50;
mcOtto._y = Stage.height-60;

// set the start speed of Otto
dX = 2;
dY = -14;
gravity = 0.3;

The dX and dY variables are the current velocity of Otto. By adding these to Otto's X and Y position each frame, Otto will move across the screen. Furthermore, by adding the gravity variable to dY, we'll get a nice bouncing effect. If you increase the gravity, Otto will bounce lower.

Edit the main frame, add the following code to move our character:


// main program loop
readKeys();

moveOtto();

function readKeys() {
if ( Key.isDown(Key.LEFT) && mcTrampoline._x > 60 ) {
mcTrampoline._x -= 10;
}
if ( Key.isDown(Key.RIGHT)&& mcTrampoline._x < Stage.width-60 ) {
mcTrampoline._x += 10;
}
}

function moveOtto() {
dY += gravity;
mcOtto._y += dY;
mcOtto._x += dX;

// make otto bounce if he hits the trampoline
if ( dY > 0 && Math.abs(mcOtto._y - mcTrampoline._y) < 20
&& Math.abs(mcOtto._x - mcTrampoline._x) < 40 ) {
dY = -dY;
}

// reverse Otto's direction if he hits the edge
if ( ( mcOtto._x < 15 ) || ( mcOtto._x > Stage.width - 15 ) ) {
dX = -dX;
}

// Otto's fell off bottom of screen...reset game
if ( ( mcOtto._y > Stage.height + 20 ) ) {
gotoAndPlay("init");
}

}

Remember, this code is executed every frame.

This code simply compares the x,y coordinates of Otto and the trampoline; if they are within a specified range (40x20 pixels), we assume Otto "bounced" on the trampoline, and reverse his vertical velocity dY.

// make otto bounce if he hits the trampoline
if ( dY > 0 && Math.abs(mcOtto._y - mcTrampoline._y) < 20 && Math.abs(mcOtto._x - mcTrampoline._x) < 40 ) {
dY = -dY;
}

In summation, we have initialised Otto's position in the init frame, and in the main frame we move Otto, and check if he hits the trampoline. If so, then we "bounce" him. If he moves past the bottom of the stage Stage+20 then assume we missed Otto, and restart the game. Download tutorial-3.fla

 Next: Balloons!


 


( categories: )