Point in Polygon function troubles
Posted: Thu Jul 17, 2008 9:13 am
I'm having trouble getting point in polygon to work correctly in lua. I converted it from this C code from this site:
To this lua code:
I was testing it on a 4 sided polygon, and it works sometimes, but there are spots in the polygon where it should register as being inside but does not. I was reading about this issue and it appears that that problem is associated with variables being passed as integers and not floating points. But after further reading it seems lua should have any issues with this happening.
The best example I could find to what is happening is these pictures:

Where my defined region is the blue, but when testing if I am inside the polygon only the red part shows true.
Any ideas as to why this would be happening?
Code: Select all
int pnpoly(int nvert, float *vertx, float *verty, float testx, float testy)
{
int i, j, c = 0;
for (i = 0, j = nvert-1; i < nvert; j = i++) {
if ( ((verty[i]>testy) != (verty[j]>testy)) &&
(testx < (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) )
c = !c;
}
return c;
}
Code: Select all
function pnpoly( vertx, verty, testx, testy )
nvert = table.getn(vertx);
c = -1;
j = nvert - 1;
for i = 1, nvert do
if ( ((verty[i] > testy) ~= (verty[j] > testy)) and (testx < (vertx[j] - vertx[i]) * (testy - verty[i]) / (verty[j] - verty[i]) + vertx[i]) ) then
c = c * -1;
end
j = i;
end
return c;
end
The best example I could find to what is happening is these pictures:

Where my defined region is the blue, but when testing if I am inside the polygon only the red part shows true.
Any ideas as to why this would be happening?