This code allows elements on the screen to be pulled towards the ground, and bounce several times as gravity works on them.
Within a platform activity if you right click on the "test activity" (green triangle) you can add the following code;
var gravity:Number = 2;
var velocity:Number = 0;
These are two defined variables - gravity and velocity. Gravity is a constant downward acceleration, set to 2. Velocity is the current vertical speed of the object in question.
Now select an element. Right click on it then click on the green rotation arrow below the image to view the animation options that are attached to the apple. Click on the red fish (for animation settings) and click on the "adv" option. in the script box that appears, enter the following code;
if ( this._y >= 453 and _root.velocity < 2.5 and _root.velocity >= 0 ) { this._y = 460; _root.velocity =0; }
else {
if ( this._y >= 460 and _root.velocity>0 ) { _root.velocity = -_root.velocity * .7 ; }
this._y += _root.velocity;
_root.velocity += _root.gravity;
}
Here is an explanation of how this works from Dan at 2Simple;
Look at the last 2 lines first. Every moment, unless the object is near the floor, (1) that object should move up or down by its current velocity, and (2) its velocity should be changed by the gravity value.
Look at the 3rd last line: If the object has reached the floor and is still heading downward, make it "bounce" - change its velocity be the negative of what it currently is, multiplied by a damping factor so it loses height each time it bounces.
Look at the first line: If the object is close to the floor and is heading downward *slowly*, make it come to rest on the floor.
View example; Download Gravity
Recent Comments