Search code examples
lua

check if point lies in polygon lua


How to check if a point lies inside a polygon or some other shapes like star? Anything with multiple vertices but they are connected. After googling for straight 2 hours. This is the code I came up with so far. It's not working the way I want it to work. Sometimes it returns true even if the point does not lie inside polygon. Here's the code.

function isPlayerinBounds (point, vertices)
    local len = #vertices
    local j = 0
    for i=1, len do
        if i == 1 then
            j = len -1
        end

        local result = false
        local ix, iy, jx, jy = vertices[i][1], vertices[i][2], vertices[j][1], vertices[j][2]

        local tx, ty = point[1], point[2]

        if(((iy< ty and jy>=ty) or (jy< ty and iy>=ty) and (ix<=tx or jx<=tx)) then

            j = i
            return true

        end

    end


    return false

end

It can be something like this


Solution

  • Your code is wrong. It tries to implement the ray casting algorithm that counts how many times a horizontal ray crosses the polygon, but your code returns as soon as it finds a crossing.

    You need to replace return true with result = not result and return result at the bottom

    Check the code in Determining Whether A Point Is Inside A Complex Polygon, on which your code seems to be based.