polypoint

Polygon Point Collision Detection

here is the original love2d forum thread: [1]

here is the original source website, beware its written in C++ [2]

The code below is a function that is called to return true when a point is within the vertices of a polygon and false otherwise. The math used is the Jordan Curve Theorem --> [3]

 function polyPoint(vertices,px,py)
 local collision = false
 local next = 1
  for current = 1, #vertices do
    next = current + 1
    if (next > #vertices) then
      next = 1
    end
    local vc = vertices[current]
    local vn = vertices[next]
    if (((vc.y >= py and vn.y < py) or (vc.y < py and vn.y >= py)) and
    (px < (vn.x-vc.x)*(py-vc.y) / (vn.y-vc.y)+vc.x)) then
        collision = not(collision)
    end
  end
  return collision
 end

Note: The code assumes your polygon vertices are stored in a table with tuples or pairs of x and y like this.

 v = {}
 v[1] = {x = 200,y = 100}
 v[2] = {x = 400,y = 130}
 v[3] = {x = 350,y = 300}
 v[4] = {x = 250,y = 300}

You can find the .love here for an example. Love Version 11.3 [4]