Created
September 17, 2010 21:34
-
-
Save georgkreimer/585000 to your computer and use it in GitHub Desktop.
tests if a point is inside a polygon (ported code from c example)
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
polygon = [{:x=>0,:y=>0},{:x=>4,:y=>0},{:x=>2,:y=>2},{:x=>0,:y=>4}] | |
point0 = {:x=>0,:y=>0} | |
point1 = {:x=>0.00000000001,:y=>0.00000000001} | |
point2 = {:x=>1,:y=>1} | |
point3 = {:x=>2,:y=>2} | |
point4 = {:x=>1.99999999999,:y=>1.99999999999} | |
# http://www.visibone.com/inpoly/ | |
# http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html | |
# | |
# 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; | |
# } | |
def point_in_polygon?(point, polygon) | |
inside = false | |
(1...polygon.size).each do |index| | |
if (((polygon[index-1][:y] > point[:y]) != (polygon[index][:y] > point[:y])) && | |
(point[:x] < (polygon[index-1][:x]-polygon[index][:x])*(point[:y]-polygon[index-1][:y])/(polygon[index][:y]-polygon[index-1][:y])+polygon[index-1][:x])) | |
inside = !inside | |
end | |
end | |
inside | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment