Difference between revisions of "polypoint"

 
(One intermediate revision by the same user not shown)
Line 1: Line 1:
'''Polygon Point Collision Detection'''
+
===Polygon Point Collision Detection===
  
 
here is the original love2d forum thread:
 
here is the original love2d forum thread:
Line 44: Line 44:
  
 
[[Category:Snippets]]
 
[[Category:Snippets]]
 +
{{#set:LOVE Version=any}}
 +
{{#set:Description=Function determines whether a point lies inside a polygon using the Jordan Curve Theorem.}}

Latest revision as of 17:28, 3 December 2024

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]