TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
 Specialized Dev Zones Research Center eBook Library .NET Java C++ Web Dev Architecture Database Security Open Source Enterprise Mobile Special Reports 10-Minute Solutions DevXtra Blogs Slideshow

# Cool DHTML: Animating Objects Within Irregular Shapes

## This article shows you how to use JavaScript and DHTML to animate a small ball within an arbitrary closed area, and provides a simple solution for determining the bounce angle of the ball from any point on the border of the enclosing area.

 by Gene Pinski
 Aug 20, 2003
 Page 1 of 4

ome years ago I was faced with a very interesting and unusual problem: how to describe the infinite movement of a ball within an arbitrary closed area. The problem seemed intractable, because it involved calculating the reflection angle and speed of the ball (a bounce) whenever it encountered any arbitrary point on an arbitrary border. Unfortunately, performing those calculations involved rather complex calculations and would have slowed the code down so much that it would become infeasible. In addition, the solution for the ball's reflection from any sharp corner would become undefined.

Finally, I realized that I could solve the problem using a completely opposite approach—rather than describing the reflection of the ball from the border, you can describe the reflection of the border from the ball!

Consider a ball moving in a certain direction. By tracking down the points on the front side of the ball, and finding out which one of them leaves the area first, you can then consider that point approximately as the point of the next collision. Therefore, the direction of the ball's movement after the collision may be calculated from that rather easily (see Figure 1).