Hi everyone,
I was looking through some old FLAs, and I stumbled upon an old bouncing ball project that I had unfinished. I updated it to AS3, and I’ve attached the source files below.
I tried to use the actual physics equations for doing all of this, so I didn’t take a more elegant route that used +=, 1/number, etc. I took a convoluted route that makes more sense on paper but less sense when used in Flash.
package {
import flash.display.*;
import flash.events.*;
public class BlueBall extends MovieClip {
var timer:Number=0;
var initialPos:Number=0;
var finalPos:Number=0;
var currentPos:Number=0;
var initialSpeed:Number=0;
var startPosition:Number = 0;
function BlueBall() {
startFallingBall();
setupResetFunctionality();
}
// Responsible for moving the ball down
function moveBallDown(e:Event) {
timer+=1;
this.y = initialPos + .5 *(timer * timer);
checkBottomBoundary();
}
// Responsible for moving the ball up
function moveBallUp(e:Event) {
timer+=1;
var posA=this.y;
this.y = currentPos - initialSpeed*timer + .5*(timer * timer);
var posB=this.y;
checkTopBoundary(posA, posB);
}
// Checks when the ball has hit the bottom
function checkBottomBoundary() {
if (this.y+this.height>stage.stageHeight) {
finalPos=this.y;
stopFallingBall();
}
}
// Checks when the ball has hit the top of the bounce
function checkTopBoundary(firstPos:Number, secondPos:Number) {
if (secondPos>firstPos) {
stopRisingBall();
startFallingBall();
}
}
// Sets up what is needed to start the falling motion
function startFallingBall() {
timer=0;
initialPos=this.y;
this.addEventListener(Event.ENTER_FRAME, moveBallDown);
}
// Stops the ball from falling and sets up the bounce provided
// the ball isn't too close to the end of its journey
function stopFallingBall() {
this.removeEventListener(Event.ENTER_FRAME, moveBallDown);
// If the bounce is a 10% of the ball's height, just stop
// the bounce
if (finalPos-initialPos<.1*this.height) {
stopRisingBall();
} else {
startRisingBall();
}
}
// Sets up what is needed to start bouncing the ball up
function startRisingBall() {
initialSpeed=Math.sqrt(Math.abs(finalPos-initialPos));
timer=0;
currentPos=this.y;
this.addEventListener(Event.ENTER_FRAME, moveBallUp);
}
// Removes the event listener for moving the ball up
function stopRisingBall() {
this.removeEventListener(Event.ENTER_FRAME, moveBallUp);
}
// Stops all ball movement
function stopEverything() {
this.removeEventListener(Event.ENTER_FRAME, moveBallUp);
this.removeEventListener(Event.ENTER_FRAME, moveBallDown);
}
//
// Ignore this unless you are interested in seeing how to restart
// the ball bounce/fall when you click on it.
//
function setupResetFunctionality() {
startPosition = this.y;
this.buttonMode = true;
this.addEventListener(MouseEvent.CLICK, ResetMovement);
}
function ResetMovement(e:MouseEvent) {
this.y = startPosition;
startFallingBall();
}
}
}