Bouncing Ball
by Administrator on Oct.25, 2010, under Scripting
In this tutorial we are going to model a bouncing ball using the equations of Newtonian physics no less! This is the result:
First let us create a new animation with size 400 x 300 using the File > Document Properties menu.
Next we draw the ball with the sphere tool. Next we group the ball as a MovieClip.
Next with the ball selected we go to the Action menu and in the MovieClip Events we choose onLoad to set up some values for when the ball first appears on the screen. In the action box we type in:
gravity = 4
velocity = {x:10, y:0}
This sets the strength of the gravitational force to a suitable number and adjusts it for 24 frames a second animation. It sets the initial velocity to a sideways direction in the x-axis.
We close this window. Then in the MovieClip Events we choose onEnterFrame which tells the ball what to do on every frame. We type in:
//the velocity increases downwards every frame
velocity.y += gravity
//the position of the ball change with the velocity
_x += velocity.x
_y += velocity.y
//if it hits the floor reverse the downward velocity
if( _y + _height/2 > Stage.height){
velocity.y*= -1
_y=Stage.height -_height/2
}
//if it hits the sides reverse the sideways velocity
if( _x - _width/2 < 0 || _x + _width/2 > Stage.width){
velocity.x*= -1
}
Close the action window and preview the result!
(You may notice that when it hits the floor we also adjust the position of the ball so it touches the floor exactly. This prevents unusual behaviour such as the ball bouncing higher then it fell.)