To simulate a bouncing ball, the following techniques were used:
const gravityConstant:Number = 4;
const floorY:int = 300;
// Set variables and constants related to the ball:
var ball_mc:Ball = new Ball();
const ballStartX:Number = 0;
const ballEndX:Number = 750;
const ballStartY:Number = 50;
var attemptedVelocityY:Number = 0;
var attemptedPositionY:Number = ballStartY;
var velocityY:Number = 0;
const velocityX:Number = 7;
ball_mc.x = ballStartX;
ball_mc.y = ballStartY;
// Set variables and constants related to the ball's shadow:
var shadow_mc:Shadow = new Shadow();
const shadowOffsetX:Number = 20;
const shadowStartX:Number = ballStartX + shadowOffsetX;
const shadowStartY:Number = floorY + 60;
shadow_mc.x = shadowStartX;
shadow_mc.y = shadowStartY;
shadow_mc.scaleX = .5;
shadow_mc.scaleY = .5;
shadow_mc.alpha = .2;
// Create a floor:
var floor:Sprite = new Sprite();
floor.graphics.beginFill(0x000000, .05);
floor.graphics.drawRect(0,300,700,450)
addChild(floor);
addChild(ball_mc);
addChild(shadow_mc);
ball_mc.addEventListener(Event.ENTER_FRAME, bounceBall);
function bounceBall(myEvent:Event):void
{
attemptedVelocityY = velocityY + gravityConstant;
attemptedPositionY = ball_mc.y + attemptedVelocityY;
if (attemptedPositionY > floorY)
{
// since ball hit floor, velocity now does a 180 to face upward into the air.
// upon impact with floor, the ball flattens slightly.
velocityY = attemptedVelocityY;
velocityY = velocityY * -1;
ball_mc.y = floorY; // so that ball doesn't sink below floor
ball_mc.scaleX = 1.2;
ball_mc.scaleY = .8;
}
else
{
velocityY = attemptedVelocityY;
ball_mc.y = attemptedPositionY;
ball_mc.scaleX = 1;
ball_mc.scaleY = 1;
}
if (ball_mc.x > ballEndX)
{
ball_mc.x = 0;
}
else
{
ball_mc.x += velocityX;
}
// Add a little motion to the shadow to make it look more natural:
shadow_mc.x = ball_mc.x + shadowOffsetX + ((ballStartY - ball_mc.y)/10);
shadow_mc.y = shadowStartY + ((ballStartY - ball_mc.y)/30);
}