Monday, 7 November 2011

Bouncing ball effect in Actionscript 3

I was contacted with a question about how to create a bouncing ball effect in Actionscript 3. I previously wrote a pendulum effect tutorial where I used the Math.sin() method with the rotation property of a movie clip to create the pendulum swing effect. This code can be reused to create the bouncing effect, but instead of using the rotation property, you use the y property to create the up and down motion.

var angle:Number = 0;
var startY:int = stage.stageHeight/2;
var range:int = 10;

addEventListener(Event.ENTER_FRAME, ef);

function ef(e:Event):void{ 
 ball.y = startY + Math.sin(angle) * range;

The code above creates a non stop continuous motion. To create a more realistic bounce motion, you can add gravity which will bring the ball to a gradual stop.

var gravity:Number = 0.2;
var vy:Number = 0;

addEventListener(Event.ENTER_FRAME, ef);

function ef(e:Event):void{
 vy += gravity;
 ball.y += vy;
 if(ball.y > stage.stageHeight - ball.height/2){
  ball.y = stage.stageHeight - ball.height/2;
  vy *= -0.6;


  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP