In case Flash no longer exists; a copy of this site is included in the Flashpoint archive's "ultimate" collection.

Dead Code Preservation :: Archived AS3 works from wonderfl.net

Bouncing Ball

Re: http://board.flashkit.com/board/showthread.php?t=797453
@author makc
@license WTFPLv2
Get Adobe Flash player
by makc3d 07 Oct 2009

    Talk

    geckzilla at 17 Oct 2009 23:26
    friction does not exist in this poor ball's world.
    makc3d at 22 Oct 2009 10:25
    it's not like it is a ton of code to add it... so... you know where the "fork" button is
    Embed
package  {
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.geom.Point;

	/**
	 * Re: http://board.flashkit.com/board/showthread.php?t=797453
	 * @author makc
	 * @license WTFPLv2
	 */
	public class BouncingBall extends Sprite{
		public function BouncingBall () {
			r = 10;
			ball = new Shape;
			ball.graphics.beginFill (0);
			ball.graphics.drawCircle (0, 0, r);
			addChild (ball);
			v = new Point;
			v.x = Math.random ();
			v.y = Math.random ();
			V = 1 + 20 * Math.random ();
			v.normalize (V);
			R = 200; X = 465 / 2; Y = 465 / 2;
			graphics.lineStyle (0);
			graphics.drawCircle (X, Y, R);
			ball.x = X + 100;
			ball.y = Y - 100;
			addEventListener ("enterFrame", loop);
		}
		private var r:Number;
		private var ball:Shape;
		private var v:Point;
		private var V:Number;
		private var R:Number;
		private var X:Number;
		private var Y:Number;
		private function loop (e:*):void {
			ball.x += v.x;
			ball.y += v.y;
			// R-r vector
			var P:Point = new Point (X - ball.x, Y - ball.y);
			if (P.length > Math.sqrt ((R - r) * (R - r))) {
				// normalize R-r vector
				P.normalize (1);
				// project v onto it
				var vp:Number = v.x * P.x + v.y * P.y;
				// subtract projection
				v.x -= 2 * vp * P.x;
				v.y -= 2 * vp * P.y;
				v.normalize (V);
				// move away from bounding circle
				P = new Point (X - ball.x, Y - ball.y);
				while (P.length > Math.sqrt ((R - r) * (R - r))) {
					ball.x += v.x;
					ball.y += v.y;
					P = new Point (X - ball.x, Y - ball.y);
				}
			}
		}
	}
}