This Actionscript 3 function returns some properties that are about a line-to-polygon intersection.
It's useful for knowing all intersection points of a segment intersecting with a polygon, and knowing if the end points of the segment are inside the polygon.

This uses the "lineIntersectLine" function of the earlier post.

 
/*---------------------------------------------------------------------------
Returns an Object with the following properties:
intersects        -Boolean indicating if an intersection exists.
start_inside      -Boolean indicating if Point A is inside of the polygon.
end_inside       -Boolean indicating if Point B is inside of the polygon.
intersections    -Array of intersection Points along the polygon.
centroid          -A Point indicating "center of mass" of the polygon.
 
"pa" is an Array of Points.
----------------------------------------------------------------------------*/
function lineIntersectPoly(A : Point, B : Point, pa:Array):Object {
	var An:int=1;
	var Bn:int=1;
	var C:Point;
	var D:Point;
	var i:Point;
	var cx:Number=0;
	var cy:Number=0;
	var result:Object = new Object();
	pa.push(pa[0]);
	result.intersects = false;
	result.intersections=[];
	result.start_inside=false;
	result.end_inside=false;
	var n:int=pa.length-1;
	while(n > -1){
		C=Point(pa[n]);
		if(n > 0){
			cx+=C.x;
			cy+=C.y;
			D=Point(pa[n-1])||Point(pa[0]);
			i=lineIntersectLine(A,B,C,D);
			if(i != null){
				result.intersections.push(i);
			}
			if(lineIntersectLine(A,new Point(C.x+D.x,A.y),C,D) != null){
				An++;
			}
			if(lineIntersectLine(B,new Point(C.x+D.x,B.y),C,D) != null){
				Bn++;
			}
		}
		n--;
	}
	if(An % 2 == 0){
		result.start_inside=true;
	}
	if(Bn % 2 == 0){
		result.end_inside=true;
	}
	result.centroid=new Point(cx/(pa.length-1),cy/(pa.length-1));
	result.intersects = result.intersections.length > 0;
	return result;
}
 
Leave a Comment

Thanks for visiting www.keith-hair.net