I’m trying to test of a point is inside of a Quadrilateral, as defined by four points.
I found some script on another site in another language and tried converting it, but I doesn’t seem to work. It might be that I don’t understand what their “sign()” method does. I thought it was Math.sin().
Site: http://gmc.yoyogames.com/index.php?showtopic=409110
Code:
import flash.events.MouseEvent;
import flash.display.Shape;
import flash.geom.Point;
var points:Vector.<Point> = new Vector.<Point>();
var shape:Shape = new Shape();
addChild(shape);
stage.addEventListener(MouseEvent.CLICK, addPoint);
function isPointInQuad(point1, point2, point3, point4, testPoint)
{
var a:Number = (point1.x - testPoint.x) * (point2.y - testPoint.y) - (point2.x - testPoint.x) * (point1.y - testPoint.y);
var b:Number = (point2.x - testPoint.x) * (point3.y - testPoint.y) - (point3.x - testPoint.x) * (point2.y - testPoint.y);
var c:Number = (point3.x - testPoint.x) * (point4.y - testPoint.y) - (point4.x - testPoint.x) * (point3.y - testPoint.y);
var d:Number = (point4.x - testPoint.x) * (point1.y - testPoint.y) - (point1.x - testPoint.x) * (point4.y - testPoint.y);
return (Math.sin(a) == Math.sin(b) && Math.sin(b) == Math.sin(c) && Math.sin(c) == Math.sin(d));
}
//This will draw a Quadrilateral with your mouse clicks, and the fifth time you click,
//it tests of that point is inside the Quadrilateral you drew.
function addPoint(e:MouseEvent):void
{
trace(points.length);
switch(points.length)
{
case 0:
shape.graphics.lineStyle(1);
shape.graphics.beginFill(0xffffff);
shape.graphics.moveTo(e.target.mouseX, e.target.mouseY);
case 1: case 2: case 3:
shape.graphics.lineTo(e.target.mouseX, e.target.mouseY);
points.push(new Point(e.target.mouseX, e.target.mouseY));
break;
case 4:
shape.graphics.endFill();
trace( isPointInQuad(points[0], points[1], points[2], points[3], new Point(e.target.mouseX, e.target.mouseY)) );
}
}
Anyone have any thoughts? I want this function to be as memory efficient as possible, but I also don’t understand the math in involved very well. I see some more complicated math for polygons, but it needs to be fast.