BilliardBall class

One of the questions I get asked more than anything else is, “I did your gravity tutorial, and I have several balls bouncing around on stage. But how do I make them realistically bounce off of each other?”

This is a bit more advanced of a topic. First you need some kind of loop that efficiently checks all balls against all other balls for collision, with no double checking. Then you need the actual code to check if they are hitting. If you get a hit, you need to reposition the balls so they are not overlapping, then you need to figure out their resulting velocities. The last part is the toughest, and relies on the conservation of momentum, coordinate and vector rotation, and can vary with the mass and size of the balls.

Finally, I sat down and wrote a BilliardBall class. All you have to do is export a movie clip, assigning it this class. Place as many balls as you want on the stage, and give each a vx and vy (velocity on each axis). There you go, near perfect collisions!

It allows for balls of different sizes – simply resize the ball. It allows for balls of different masses, just set the “mass” property of any ball (defaults to 1). You can set a “bounce” property (generally 0 to -1) and a “damp” property (0 to 1) as friction. “setBounds” sets the walls of the universe where the balls live, and defaults to the stage size. The “grav” property adds velocity on the y axis, to make the balls fall down (use negative number to add lift). You can also make any particular ball draggable and throwable by setting the “draggable” property to true.

Ball motion and the collision detection loop are handled with setInterval, so each ball’s onEnterFrame is still available for you to use as you wish. The interval can be set with a static class property: com.bit101.BilliardBall.refreshRate = 10; for example.

Here is is: http://www.bit-101.com/classes/BilliardBall.as

This entry was posted in Flash. Bookmark the permalink.

One Response to BilliardBall class

  1. Broots says:

    I gotta say dude, your flash site is totally awesome! 🙂 Excellent work!

Comments are closed.