Cool DHTML: Animating Objects Within Irregular Shapes
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 approachrather 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).