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

Approximate ellipse-to-ellipse hit test

Get Adobe Flash player
by makc3d 03 Mar 2011
    Embed
package {
	import com.bit101.components.HSlider;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Point;
	public class ApproximateEllipse2EllipseHitTestTest extends Sprite {
		public function ApproximateEllipse2EllipseHitTestTest () {
			addChild (s1 = new Sprite);
			addChild (s2 = new Sprite);
			addEventListener (Event.ENTER_FRAME, loop);
			new HSlider (this, 20, 440, function (e:Event):void {
				a = b * e.target.value / 2;
			}).setSliderParams (2, 10, 3);
		}
		private function loop (e:Event):void {
			s1.x = 100;
			s1.y = 100;
			s1.rotation ++;
			s2.x = mouseX;
			s2.y = mouseY;
			// location of s1 in s2 coords
			var loc12:Point = s2.globalToLocal (new Point (s1.x, s1.y));
			// location of s2 in s1 coords
			var loc21:Point = s1.globalToLocal (new Point (s2.x, s2.y));
			// approximate hittest?
			var dx12:Number = loc12.x / a, dy12:Number = loc12.y / b;
			var dx21:Number = loc21.x / a, dy21:Number = loc21.y / b;
			hit = (dx12 * dx12 + dy12 * dy12 + dx21 * dx21 + dy21 * dy21 < 2);
			drawEllipse (s1);
			drawEllipse (s2);
		}
		private var s1:Sprite;
		private var s2:Sprite;
		private var a:Number = 60;
		private var b:Number = 40;
		private var hit:Boolean;
		private function drawEllipse (s:Sprite):void {
			s.graphics.clear ();
			s.graphics.beginFill (hit ? 0xFF00 : 0xFF0000);
			s.graphics.moveTo (-a/2, 0);
			for (var i:int = -4; i < 6; i++) {
				s.graphics.lineTo (a * i / 10, +b * Math.sqrt (1 - i * i / 25) / 2);
			}
			for (i = 4; i > -6; i--) {
				s.graphics.lineTo (a * i / 10, -b * Math.sqrt (1 - i * i / 25) / 2);
			}
			s.graphics.endFill ();
		}
	}
}