# Line Intersection Part 1 (unoptimized)

Actionscript:
1. // completely unoptimized line to line intersection test:
2. // from wikipedia: http://en.wikipedia.org/wiki/Line-line_intersection
3. function intersection(p1:Sprite, p2:Sprite, p3:Sprite, p4:Sprite):Point {
4.     var nx:Number, ny:Number, dn:Number;
5.     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);
6.     dn = (p1.x - p2.x) * (p3.y - p4.y) - (p1.y - p2.y) * (p3.x - p4.x);
7.     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);
8.     return new Point(nx / dn, ny / dn);
9. }
10.
11. //
12. // test out the function:
13. //
14.
15. stage.frameRate = 30;
16. var a:Sprite = dot();
17. a.x = a.y = 100;
18.
19. var b:Sprite = dot();
20. b.x = b.y = 200;
21.
22. var c:Sprite = dot();
23. c.x = 200
24. c.y = 100;
25.
26. var d:Sprite = dot();
27. d.x = 100
28. d.y = 200;
29.
30. var inter:Sprite = dot(0xFF0000,true);
31.
33. function onLoop(evt:Event):void {
34.     var p:Point = intersection(a, b, c, d);
35.     inter.x = p.x;
36.     inter.y = p.y
37.
38.     with(graphics){
39.         clear();
40.         lineStyle(0,0x000000);
41.         moveTo(a.x, a.y);
42.         lineTo(b.x, b.y);
43.         moveTo(c.x, c.y);
44.         lineTo(d.x,d.y);
45.     }
46. }
47.
48. // draggable dot
49. function dot(col:uint = 0x507399, noDrag:Boolean = false):Sprite {
50.     var s:Sprite = Sprite(addChild(new Sprite));
51.     with(s.graphics) beginFill(col), drawCircle(0,0,5);
52.     if (!noDrag){
53.         s.buttonMode = true;
55.     }
56.     return s;
57. }
58. function onDrag(evt:MouseEvent):void {
59.     evt.currentTarget.startDrag()
60. }
61.
63. function onUp(evt:MouseEvent):void{
64.     stopDrag();
65. }

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