-
// completely unoptimized line to line intersection test:
-
// from wikipedia: http://en.wikipedia.org/wiki/Line-line_intersection
-
function intersection(p1:Sprite, p2:Sprite, p3:Sprite, p4:Sprite):Point {
-
var nx:Number, ny:Number, dn:Number;
-
nx = (p1.x * p2.y - p1.y * p2.x) * (p3.x - p4.x) - (p1.x - p2.x) * (p3.x * p4.y - p3.y * p4.x);
-
dn = (p1.x - p2.x) * (p3.y - p4.y) - (p1.y - p2.y) * (p3.x - p4.x);
-
ny = (p1.x * p2.y - p1.y * p2.x) * (p3.y - p4.y) - (p1.y - p2.y) * (p3.x * p4.y - p3.y * p4.x);
-
return new Point(nx / dn, ny / dn);
-
}
-
-
//
-
// test out the function:
-
//
-
-
stage.frameRate = 30;
-
var a:Sprite = dot();
-
a.x = a.y = 100;
-
-
var b:Sprite = dot();
-
b.x = b.y = 200;
-
-
var c:Sprite = dot();
-
c.x = 200
-
c.y = 100;
-
-
var d:Sprite = dot();
-
d.x = 100
-
d.y = 200;
-
-
var inter:Sprite = dot(0xFF0000,true);
-
-
addEventListener(Event.ENTER_FRAME, onLoop);
-
function onLoop(evt:Event):void {
-
var p:Point = intersection(a, b, c, d);
-
inter.x = p.x;
-
inter.y = p.y
-
-
with(graphics){
-
clear();
-
lineStyle(0,0x000000);
-
moveTo(a.x, a.y);
-
lineTo(b.x, b.y);
-
moveTo(c.x, c.y);
-
lineTo(d.x,d.y);
-
}
-
}
-
-
// draggable dot
-
function dot(col:uint = 0x507399, noDrag:Boolean = false):Sprite {
-
var s:Sprite = Sprite(addChild(new Sprite));
-
with(s.graphics) beginFill(col), drawCircle(0,0,5);
-
if (!noDrag){
-
s.buttonMode = true;
-
s.addEventListener(MouseEvent.MOUSE_DOWN, onDrag);
-
}
-
return s;
-
}
-
function onDrag(evt:MouseEvent):void {
-
evt.currentTarget.startDrag()
-
}
-
-
stage.addEventListener(MouseEvent.MOUSE_UP, onUp);
-
function onUp(evt:MouseEvent):void{
-
stopDrag();
-
}
This snippet shows the first step toward a usable line to line intersection test. While this demo is fully functional, there is some room for optimization within the intersection() function itself...
From Equations to Code
When I go directly from an equation to code I like to try to make the code resemble the equation... test to make sure it works and then add optimizations. I do this to keep things clear for myself and also so that I have a step by step process to show my students.
The optimizations and additional features that I'll add to this function tomorrow will make it look very different from the original equation from wikipedia. Some things that I'll do:
1) tweak the equation to use fewer operators (it has 12 multiplications right now)
2) wrap duplicate mathmatical operations in variables
3) add the ability to test for line segments rather than infinite lines
4) move any object instantiation outside the function
etc...