Tutorials, extensions, and source files for ActionScript, Flash, and other Adobe products.

 

senocular.com ActionScript Library

lineIntersection.as

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// ver1 using individual point locations and a _x _y return point value

lineIntersection = function (x1, y1, x2, y2, x3, y3, x4, y4, segment) {
	var p={}, d1 = x2-x1, d2 = x4-x3;
	if (!d1){
		if (!d2) return false;
		p._x = x1; p._y = y3+(y4-y3)*(x1-x3)/d2;
	}else if (!d2){
		p._x = x3; p._y = y1+(y2-y1)*(x3-x1)/d1;
	}else{
		var m1 = (y2-y1)/d1, m2 = (y4-y3)/d2;
		if (m1 == m2) return false;
		var c1 = y1-m1*x1, c2 = y3-m2*x3;
		var d = m2-m1;
		p._x = (c1-c2)/d; p._y = (m2*c1-m1*c2)/d;
	}
	if (segment){
		if (d1>0){
			if (p._x<x1 || p._x>x2) return false;
		}else if (d1<0){
			if (p._x>x1 || p._x<x2) return false;
		}else if ((p._y<y1 && p._y<y2) || (p._y>y1 && p._y>y2)) return false;
		if (d2>0){
			if (p._x<x3 || p._x>x4) return false;
		}else if (d2<0){
			if (p._x>x3 || p._x<x4) return false;
		}else if ((p._y<y3 && p._y<y4) || (p._y>y3 && p._y>y4)) return false;
	}
	return p;
}

// ver 2 using x,y point objects, passed and returned
lint=function (s1, e1, s2, e2, seg) {
	var p={}, d1=e1.x-s1.x, d2=e2.x-s2.x;
	if (!d1){
		if (!d2) return false;
		p.x=s1.x; p.y=s2.y+(e2.y-s2.y)*(s1.x-s2.x)/d2;
	}else if (!d2){
		p.x=s2.x; p.y=s1.y+(e1.y-s1.y)*(s2.x-s1.x)/d1;
	}else{
		var m1=(e1.y-s1.y)/d1, m2=(e2.y-s2.y)/d2;
		if (m1 == m2) return false;
		var c1=s1.y-m1*s1.x, c2=s2.y-m2*s2.x;
		var d=m2-m1;
		p.x=(c1-c2)/d; p.y=(m2*c1-m1*c2)/d;
	}
	if (seg){
		if (d1>0){
			if (p.x<s1.x || p.x>e1.x) return false;
		}else if (d1<0){
			if (p.x>s1.x || p.x<e1.x) return false;
		}else if ((p.y<s1.y && p.y<e1.y) || (p.y>s1.y && p.y>e1.y)) return false;
		if (d2>0){
			if (p.x<s2.x || p.x>e2.x) return false;
		}else if (d2<0){
			if (p.x>s2.x || p.x<e2.x) return false;
		}else if ((p.y<s2.y && p.y<e2.y) || (p.y>s2.y && p.y>e2.y)) return false;
	}
	return p;
}