ActionScript.org Flash, Flex and ActionScript Resources - http://www.actionscript.org/resources
Bouncing ball with particle effect and wind
http://www.actionscript.org/resources/articles/706/1/Bouncing-ball-with-particle-effect-and-wind/Page1.html
Alejandro Quarto
Partner, Software Development/General Manager at Persuasive Games. In his role, Mr. Quarto is responsible for software development and testing, as well as studio management and strategy.
Prior to joining to Persuasive Games, Mr. Quarto started his career in interactive entertainment as a freelance programmer using different object-oriented programming tools specifically specializing in Macromedia Flash, Shockwave, and Java development platforms among others. In 2002 Mr. Quarto co-founded Platico Games! in Buenos Aires, Argentina. While at Platico Games Studio, Mr. Quarto produced a wide variety of video game projects including: advergames, educational games, and multiplayer games oriented to big communities.
These games have been developed for clients such as: Claxson Interactive Group, Budweiser, Mattel, Turbo Video Brazil, Canal 13 (TV) Argentina, and FM HIT in Chile. 
Quarto is currently teaching about Flash development, in an institute located in Buenos Aires. In his role as instructor, he teach how to develop webs and games, for online content. Personal Blog: http://www.alejandroquarto.com

 
By Alejandro Quarto
Published on November 30, 2007
 
This tutorial will try to explain the basic physics behind a ball. We will introduce a simple particle effect with movie clip duplication, and also a way to command the ball with the keyboard.
This tutorial requires ActionScript 2.0, and Flash 8 at least.

How is the example supposed to work
I hope this help you to learn something. You can check in my blog for more examples like this one (www.alejandroquarto.com)
First you should take a look to the final swf, if everything goes fine, you should be able to create something like this: (MOUSE and ARROW KEYS)



Note that if you use the mouse, it will work as a wind effect. It means: mouse will move the ball in the opposite direction that exists between the mouse and the ball.
If you are really near, force will be very high compared with a big distance.

Then, if you want to see how the ball move and bounce, you can use your keyboard and move it with the arrows keys.

Main idea behind this example is to introduce some physic criteria and forces. Every thing you do to move the ball is basically to apply a force to the ball. There are also external things like gravity, or friction.

Play a bit with the ball, if you like it, let's start with ActionScript.


Creating the ball and the particle
Since we want to be able to have a nice ball in the screen, i suggest to create it in vector art. Once you get the draw, just press F8, and convert it to MovieClip. Is important to define an identifier in the dialog box. Press the "Export for ActionScript" check-box, and type "circle" in the identifier text field.
OK, you got a movie, and now you are able to introduce it inside the scene by using ActionScript, so basically, you just need the movie inside the library (Ctrl+L), let's remove this ball from the scene.
Now, we are going to use another movie for the particle. In this example i just used another color, but you can do whatever you want. Repeat the same process you made for the ball, but now instead "circle", use the "circleParticle" identifier.
That's all for now, if you have two movies in the library and nothing in the scene, then you are OK. Keep moving.

Adding code to the ball
Now, we need to introduce some code to the ball. Take a look to the code, i will explain later.

restitution = 0.7; resistence = 0.997; acceleration_x = 0; acceleration_y = 0; gravity = 0.2; particleCount = 0; this.onEnterFrame = function() { generateParticles(); this.swapDepths(_parent.getNextHighestDepth()) acceleration_y += gravity; acceleration_y *= resistence; acceleration_x *= resistence; checkColision(); _x += acceleration_x; _y += acceleration_y; }; function accelerate(x, y) { acceleration_x += x; acceleration_y += y; } function checkColision() { if (_x+acceleration_x+(_width/2)>=_parent.rightLimit) { if (_x+(_width/2)<_parent.rightLimit) { _x = _parent.rightLimit-(_width/2)-0.1; } else { acceleration_x *= -1*restitution; } } if (_x+acceleration_x-(_width/2)<=_parent.leftLimit) { if (_x-(_width/2)>_parent.leftLimit) { _x = _parent.leftLimit+(_width/2)+0.1; } else { acceleration_x *= -1*restitution; } } if (_y+acceleration_y+(_width/2)>=_parent.bottomLimit) { if (_y+(_width/2)<_parent.bottomLimit) { _y = _parent.bottomLimit-(_width/2)-0.1; } else { acceleration_y *= -1*restitution; } } if (_y+acceleration_y-(_width/2)<=_parent.topLimit) { if (_y-(_width/2)>_parent.topLimit) { _y = _parent.topLimit+(_width/2)+0.1; } else { acceleration_y *= -1*restitution; } } } function generateParticles() { _parent.attachMovie("circleParticle","particle"+particleCount,_parent.getNextHighestDepth(),{_x:_x, _y:_y}); particleCount++; }

This code will be in the only frame we have inside the ball.
First we need to define some physic properties: restitution is the amount of energy that the ball loses after a collision. Resistence, is basically the aerodinamic resistence. Gravity will be a constant that we are going to add to the acceleration in the Y axis. Then we have the initial acceleration in both axis. Finally particleCount is just to know how many particles the ball create.
Since we want to update the ball every frame, we use the enterFrame function.
Inside we have, the particle generation function, the depth swap, to see the ball always on top of the particles. We also add the gravity to the acceleration on axis Y. The important thing here is the collision. We want to check if the ball will collide with the limits before we move it. Cos that, we call the checkCollision function, then we add the acceleration to the _x and _y properties.

CheckCollision function, have a litle workarround. Main idea is to know if the ball plus the acceleration on each axis, will collide with the limits. Anyway on most examples arround this is a simple check, and is common to see the ball colliding even if it is not near to the limit. So, first check plus acceleration, then instead of reversing ball acceleration, we check if the ball is really colliding, if not, we place the ball in the limit, next time we just apply a -1 multiplier and the restitution factor to reduce the bouncing.

Finally we move the ball. Note that the limits vars are not yet declared. We want to have it in the _root, so if we create more balls, all will use the same vars.

We also have another function: accelerate(). This function is basically to add acceleration in both axis. We are going to use this function to move the ball in the next section.

The last function is the particle generation. Everytime is called, we attach a particle movie in the _root, in the same _X and _Y than the ball have.

Ok, time to start adding interaction!

The main code
So, now we need to attach the ball in the scene, and be able to apply some forces. Let's take a look to the code:
function init() { leftLimit = 0; rightLimit = Stage.width; bottomLimit = Stage.height; topLimit = 0; } function createBall() { this.attachMovie("circle","myCircle",_root.getNextHighestDepth(),{_x:(rightLimit-leftLimit)/2, _y:(bottomLimit-topLimit)/2}); } init(); createBall(); this.onEnterFrame = function() { //Wind angle = Math.atan2(_ymouse-myCircle._y, _xmouse-myCircle._x); distance = Math.sqrt(Math.pow(_xmouse-myCircle._x, 2)+Math.pow(_ymouse-myCircle._y, 2))/10; myCircle.accelerate(-Math.cos(angle)/distance,-Math.sin(angle)/distance); //Keyboard detection if (Key.isDown(Key.RIGHT)) { myCircle.accelerate(0.4,0); } if (Key.isDown(Key.LEFT)) { myCircle.accelerate(-0.4,0); } if (Key.isDown(Key.UP)) { myCircle.accelerate(0,-0.4); } if (Key.isDown(Key.DOWN)) { myCircle.accelerate(0,0.4); } };

First function is the limits definition, right, left, top, and bottom. I've used the scene margins.
Next function is the ball creation, attaching the ball in the center of the screen with an instance name of  "myCircle".
We call both functions, and then the enterFrame.
In the enterframe, we will apply the wind effect. We have an angle between the mouse and the ball, also a distante. So, by using math, we call the accelerate function in the ball, sending the proyections of the vector defined in polar coordinates by an angle and a module.
After the wind, we just need to capture the keys, and send forces according the arrow direction.
Is simple like that. Now we want to define the particle behaviour.


The particles
Code is really simple:

this.onEnterFrame = function() { distance=Math.sqrt((Math.pow(_alpha-0,2))+(Math.pow(_alpha-0,2)))/5; _alpha-=distance _xscale-=distance/4 _yscale-=distance/4 if(_alpha<1){ this.removeMovieClip() } }



On every frame, we do the distance calculation from the actual movie's _alpha, to 0. Using this distance we reduce the scale and the transparency. If the alpha is near to 0, we just remove the movie.
Note that if you change the "5" and "4" values, particle life time will change. Here you can play with all the movie properties and also add frames for better effects.

That's all! This is not the most realistic way, but is a good approach to a simulation with a few lines of code.

You can get more examples at my blog: www.alejandroquarto.com

Attached source code at the end of the page.