# Bounce Ball Inside a Circle

Actionscript:
1. package  {
2.     import flash.display.Shape;
3.     import flash.display.Sprite;
4.     import flash.geom.Point;
5.
6.     /**
8.      * @author makc
10.      */
11.     public class BouncingBall extends Sprite{
12.         public function BouncingBall () {
13.             r = 10;
14.             ball = new Shape;
15.             ball.graphics.beginFill (0);
16.             ball.graphics.drawCircle (0, 0, r);
18.             v = new Point;
19.             v.x = Math.random ();
20.             v.y = Math.random ();
21.             V = 1 + 20 * Math.random ();
22.             v.normalize (V);
23.             R = 200; X = 465 / 2; Y = 465 / 2;
24.             graphics.lineStyle (0);
25.             graphics.drawCircle (X, Y, R);
26.             ball.x = X + 100;
27.             ball.y = Y - 100;
29.         }
30.         private var r:Number;
31.         private var ball:Shape;
32.         private var v:Point;
33.         private var V:Number;
34.         private var R:Number;
35.         private var X:Number;
36.         private var Y:Number;
37.         private function loop (e:*):void {
38.             ball.x += v.x;
39.             ball.y += v.y;
40.             // R-r vector
41.             var P:Point = new Point (X - ball.x, Y - ball.y);
42.             if (P.length> Math.sqrt ((R - r) * (R - r))) {
43.                 // normalize R-r vector
44.                 P.normalize (1);
45.                 // project v onto it
46.                 var vp:Number = v.x * P.x + v.y * P.y;
47.                 // subtract projection
48.                 v.x -= 2 * vp * P.x;
49.                 v.y -= 2 * vp * P.y;
50.                 v.normalize (V);
51.                 // move away from bounding circle
52.                 P = new Point (X - ball.x, Y - ball.y);
53.                 while (P.length> Math.sqrt ((R - r) * (R - r))) {
54.                     ball.x += v.x;
55.                     ball.y += v.y;
56.                     P = new Point (X - ball.x, Y - ball.y);
57.                 }
58.             }
59.         }
60.     }
61. }

Makc3d said I could choose one of his excellent wonderfl.net pieces and submit it to the contest. This snippet creates a ball that bounces off the inside of a circle. I thought this was a pretty unique way to go about doing this - and found it easy to add gravity and other cool features to it.

Have a look at the swf over at wonderfl....

Makc3d elaborated on his code a bit via e-mail. He said that his technique sacrifices accuracy for simplicity... and that if you simplify too much it would be easy to break the code. "e.g. comment out piece of code where it says "move away from bounding circle""...

Here is a picture that Makc3d drew explaining why you need to multiply by 2: This entry was posted in motion and tagged , , , . Bookmark the permalink. Both comments and trackbacks are currently closed.