This article carries on the series started with
inertia effect.
We saw next how to add the
spring effect and the
friction effect.
Now, we will see the gravity and how to bounce a ball.
Follow me"
I create a FLA and save it as "gravita.fla".
Into which, I place on stage a circular MovieClip named "ball_mc".
Here is the code:
Code:
var spring:Number=.1;
var frizione:Number=.98;
var gravita:int=1;
var limite:Number=stage.stageHeight;
stage.frameRate=31;
ball_mc.velY=0;
ball_mc.oldY=0;
ball_mc.addEventListener(Event.ENTER_FRAME,go);
function go(e:Event):void
{
e.target.velY+=gravita;
e.target.velY*=frizione;
e.target.y+=e.target.velY;
if(e.target.y>limite-e.target.width/2)
{
e.target.y=limite-e.target.width/2;
e.target.velY*=-1;
}
}
Let us analyse the code
Four numerical variables which respectively contains the needed values for the effect
var spring:Number=.1;
var frizione:Number=.98;
var gravita:int=1;
var limite:Number=stage.stageHeight;
I impost the frame rate
stage.frameRate=31;
I assign two properties to "ball_mc" (the speed)
ball_mc.velY=0;
ball_mc.oldY=0;
I add ENTER_FRAME which calls the function "go"
ball_mc.addEventListener(Event.ENTER_FRAME,go);
function go(e:Event):void
{
I add the gravity to "velY" (a property assigned to "ball_mc" with an initial value equal to zero)
e.target.velY+=gravita;
I add the friction
e.target.velY*=frizione;
I add to ball_mc"s y the property "velY"
e.target.y+=e.target.velY;
I check the ball_mc"s y
if(e.target.y>limite-e.target.width/2)
{
if it is bigger then the value of the variable "limite" less half of "ball_mc" width I invert the value of "velY"
e.target.y=limite-e.target.width/2;
e.target.velY*=-1;
}
}
Stay tuned !