Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


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.


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).

Comment and Contribute








