I'm trying to check if point x, y is inside of polygon poly = {x1,y1, x2,y2, x3,y3 ...}
But something goes wrong:
local function pointInConvexPolygon(x, y, poly)
-- poly as {x1,y1, x2,y2, x3,y3, ...}
local imax = #poly
local function isVerticesClockwise(poly)
local sum = 0
local imax = #poly
local x1, y1 = poly[imax-1], poly[imax]
for i = 1, imax - 1, 2 do
local x2, y2 = poly[i], poly[i + 1]
sum = sum + (x2 - x1) * (y2 + y1)
x1, y1 = x2, y2 -- fixed
end
local isClockwise = sum < 0
love.window.setTitle(isClockwise and 'clockwise' or 'counterclockwise')
return isClockwise
end
local sign = isVerticesClockwise(poly) and 1 or -1
local x1, y1 = poly[imax-1], poly[imax]
for i = 1, imax - 1, 2 do
local x2, y2 = poly[i], poly[i + 1]
local dotProduct = (x - x1) * (y1 - y2) + (y - y1) * (x2 - x1)
if sign * dotProduct < 0 then
return false
end
x1, y1 = x2, y2
end
return true
end
Sometimes clockwise direction is right, but sometimes it says wrong direction.
The correct formula of the triangle signed area is
(x1*y2 - x2*y1)/2assuming the third vertex is at(0,0)A point is inside a convex poly when all point-edge-traingle areas are of the same sign.