Main Content
Gravity and Bounce
As you can see, the ball gradually bounces lower and lower - as it would do in real life. Although this concept may seem simple at first it is in fact only moderately simple. Not only does the ball have to bounce less and less, it must also have to accelerate as it gets closer to the ground and decelerate as it gets further away from the ground. This introduces the need for timings, something which I do not think we have covered much yet - real life timings that is - which we touched on in the setInterval function I believe.
To create the actual scenario, create a ball or whatever, and make the stage fairly tall. Convert the ball to a symbol and put it near the top of the stage. Now we can delve into the ActionScript powering this gravity effect. We start with variables:
onClipEvent (load) { gravity = 2; //Generally positive (feel free to play around) floory = 300; // Floor y - the y coordinate of the floor bounciness = 0.82; // Should be between 0 (no bounce) and 1 (regains starting height) time = getTimer(); //Gets the time for the initial drop time = time/100; //Changes the format of the time into something more useful startingspeed = 0;//Used later }
The comments should tell you what each of these variables does. The first three can be changed. Now we move onto the motion:
onClipEvent (enterFrame) { timenow = getTimer () ; timenow = timenow/100 ; speedy = gravity * (timenow - time) + startingspeed ; this._y += speedy/5 ;
The main part of the physics. Timenow is, well, the time now. The speedy thing basically correlates to:
how much to move = (gravity * how long we have been in the air) + our speed to start with
Okay? Well, anyhow, it works.The last line moves us the appropriate distance. The next section is to do with the bounce itself:
if (this._y > floory) { this._y = floory; speedy = speedy * -bounciness; time = getTimer(); time = time/100; startingspeed = speedy; } }
The if statement just says "if we are touching the floor", and then bounce. The speedy line controls the bounce - inverting the downwards speed into up speed. However the bounciness variable also deducts a bit so, in effect, it will not bounce as high as before. The last 3 lines merely reset the starting time (used for acceleration purposes earlier) and the starting speed.
Believe me, this is a realistic effect if done properly. Okay - you probably won't just have a bouncing ball, but if you incorporate some x speed as well you can get the sort of effects seen in games such as IndestructoTank. See you soon!
Harry.