Difference between revisions of "polypoint"

m (2D Polygon Collision Detection Function)
 
(2 intermediate revisions by one other user not shown)
Line 10: Line 10:
 
The math used is the Jordan Curve Theorem --> [https://en.wikipedia.org/wiki/Jordan_curve_theorem]
 
The math used is the Jordan Curve Theorem --> [https://en.wikipedia.org/wiki/Jordan_curve_theorem]
  
----
+
<source lang="lua">
[[:Lua::
+
function polyPoint(vertices,px,py)
function polyPoint(vertices,px,py)
+
local collision = false
local collision = false
+
local next = 1
local next = 1
 
 
   for current = 1, #vertices do
 
   for current = 1, #vertices do
 
     next = current + 1
 
     next = current + 1
Line 28: Line 27:
 
   end
 
   end
 
   return collision
 
   return collision
end
+
end
]]
+
</source>
  
 
Note: The code assumes your polygon vertices are stored in a table with tuples or pairs of x and y like this.
 
Note: The code assumes your polygon vertices are stored in a table with tuples or pairs of x and y like this.
  
[[:Lua::
+
<source lang="lua">
v = {}
+
v = {}
v[1] = {x = 200,y = 100}
+
v[1] = {x = 200,y = 100}
v[2] = {x = 400,y = 130}
+
v[2] = {x = 400,y = 130}
v[3] = {x = 350,y = 300}
+
v[3] = {x = 350,y = 300}
v[4] = {x = 250,y = 300}
+
v[4] = {x = 250,y = 300}
]]
+
</source>
 
 
  
 
You can find the .love here for an example. Love Version 11.3
 
You can find the .love here for an example. Love Version 11.3
 
[https://love2d.org/forums/download/file.php?id=18245]
 
[https://love2d.org/forums/download/file.php?id=18245]
 +
 +
[[Category:Snippets]]

Latest revision as of 07:17, 21 May 2020

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]