togFox wrote: ↑Mon Oct 09, 2023 11:39 pm
Did a google search on "lua code for determining if point is inside triangle" and this thread came up.
Just checking if the OP code is still considered the best? Has there been any improvements in the last two years? I'm happy to use as-is but just checking.
[I can't access 2dengine.com from my work internet]
Not sure if it faster, but it's shorter!
Code: Select all
function love.load()
v1 = {x = 200, y = 200}
v2 = {x = 400, y = 250}
v3 = {x = 250, y = 500}
inside = false
end
local function isPointInTriangle(point, v1, v2, v3)
local function calculateTriangleArea(v1, v2, v3)
return 0.5 * math.abs((v1.x - v3.x) * (v2.y - v1.y) - (v1.x - v2.x) * (v3.y - v1.y))
end
local totalArea = calculateTriangleArea(v1, v2, v3)
local area1 = calculateTriangleArea(point, v2, v3)
local area2 = calculateTriangleArea(v1, point, v3)
local area3 = calculateTriangleArea(v1, v2, point)
return math.abs(totalArea - (area1 + area2 + area3)) < 1e-6
end
function love.draw()
if inside then
love.graphics.setColor(0,1,1)
else
love.graphics.setColor(1,0,0)
end
love.graphics.line(v1.x, v1.y, v2.x, v2.y)
love.graphics.line(v2.x, v2.y, v3.x, v3.y)
love.graphics.line(v3.x, v3.y, v1.x, v1.y)
love.graphics.circle ('line', v3.x, v3.y, 5)
end
function love.mousemoved(x, y)
inside = isPointInTriangle({x=x, y=y}, v1, v2, v3)
end
function love.mousepressed(x, y)
v2, v3 = v3, v2
inside = isPointInTriangle({x=x, y=y}, v1, v2, v3)
end
or just check the polygon (triangle is a polygon too):
Code: Select all
local function pointInPolygon (px, py, ...)
local vertices = {...}
local inside = false
local j = #vertices-1
local x2, y2 = vertices[j], vertices[j+1]
for i = 1, #vertices-1, 2 do
local x1, y1 = vertices[i], vertices[i+1]
if (y1 < py and y2 >= py or y2 < py and y1 >= py)
and (x1 <= px or x2 <= px)
and (x1 + (py - y1) / (y2-y1)*(x2-x1) < px) then
inside = not inside
end
x2, y2 = x1, y1
end
return inside
end
function love.mousemoved(x, y)
inside = isPointInTriangle({x=x, y=y}, v1, v2, v3)
local inside2 = pointInPolygon (x, y, v1.x, v1.y, v2.x, v2.y, v3.x, v3.y)
love.window.setTitle (tostring (inside2))
end