Difference between revisions of "polypoint"
(2D Polygon Collision Detection Function) |
|||
(8 intermediate revisions by 3 users not shown) | |||
Line 1: | Line 1: | ||
− | + | ===Polygon Point Collision Detection=== | |
here is the original love2d forum thread: | here is the original love2d forum thread: | ||
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"> | |
− | 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 27: | Line 27: | ||
end | end | ||
return collision | return collision | ||
− | + | end | |
+ | </source> | ||
− | Note: The code assumes your polygon vertices are stored in a table with | + | Note: The code assumes your polygon vertices are stored in a table with tuples or pairs of x and y like this. |
− | v = {} | + | <source lang="lua"> |
− | v[1] = {x = 200,y = 100} | + | v = {} |
− | v[2] = {x = 400,y = 130} | + | v[1] = {x = 200,y = 100} |
− | v[3] = {x = 350,y = 300} | + | v[2] = {x = 400,y = 130} |
− | v[4] = {x = 250,y = 300} | + | v[3] = {x = 350,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]] | ||
+ | {{#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]