« Return

# ActionScript 3

## Bouncing Ball simulation using no tweens

To simulate a bouncing ball, the following techniques were used:

• The ball itself includes a highlight and shadow to make it look more 3-D (of the techniques listed here, this is the only one that involved no Action Script).
• The acceleration of gravity is simulated using code which accelerates the ball downward in each frame. This has the effect of speeding up the ball as it falls, and slowing the ball as it rises.
• When the ball hits the floor (that is, when its y-position is greater than that defined as the floor), the scaleX and scaleY are temporarily altered so that the ball flattens a bit upon impact.
• The cast shadow of the ball wobbles slightly in sync with the ball, to make the shadow look more realistic.

```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:
const shadowOffsetX:Number = 20;
const shadowStartY:Number = floorY + 60;

// Create a floor:
var floor:Sprite = new Sprite();
floor.graphics.beginFill(0x000000, .05);
floor.graphics.drawRect(0,300,700,450)

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);
}```

« Return

©2012 Kroll Design    info@KrollDesign.net    781.910.3694