Created
June 25, 2016 08:01
-
-
Save GiriB/320a4c22ab3483d0ec6500edb957380e to your computer and use it in GitHub Desktop.
"Ray Casting Method" to find if a point in a polygon in lua
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Port of http://www.ariel.com.au/a/python-point-int-poly.html in lua | |
-- # Determine if a point is inside a given polygon or not | |
-- # Polygon is a list of (x,y) pairs. This function | |
-- # returns True or False. The algorithm is called | |
-- # the "Ray Casting Method". | |
function point_inside_poly(x,y,poly) | |
-- poly is like { {x1,y1},{x2,y2} .. {xn,yn}} | |
-- x,y is the point | |
local inside = false | |
local p1x = poly[1][1] | |
local p1y = poly[1][2] | |
for i=0,#poly do | |
local p2x = poly[((i)%#poly)+1][1] | |
local p2y = poly[((i)%#poly)+1][2] | |
if y > math.min(p1y,p2y) then | |
if y <= math.max(p1y,p2y) then | |
if x <= math.max(p1x,p2x) then | |
if p1y ~= p2y then | |
xinters = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x | |
end | |
if p1x == p2x or x <= xinters then | |
inside = not inside | |
end | |
end | |
end | |
end | |
p1x,p1y = p2x,p2y | |
end | |
return inside | |
end | |
polgon = {{0,10},{10,10},{10,0},{0,0}} | |
print(point_inside_poly(10,11,polgon)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Returns
false
forprint(point_inside_poly(10,0,polgon))