Difference between revisions of "PointInConcavePolygon"

m (Added missing property for the category page. Didn't actually check if the code functions or not.)
 
Line 83: Line 83:
 
[[Category:Snippets]]
 
[[Category:Snippets]]
 
{{#set:Author=User:Ratchet}}
 
{{#set:Author=User:Ratchet}}
{{#set:Description=A function returning True if the given point is inside the given polygon.}}
+
{{#set:LOVE Version=any}}
 +
{{#set:Description=A function returning true if the given point is inside the given polygon.}}

Latest revision as of 18:10, 11 November 2016

A function returning True if the given point is inside the given polygon.

function pointInPolygon(pgon, tx, ty)
	if (#pgon < 6) then
		return false
	end

	local x1 = pgon[#pgon - 1]
	local y1 = pgon[#pgon]
	local cur_quad = getQuad(tx,ty,x1,y1)
	local next_quad
	local total = 0
	local i

	for i = 1,#pgon,2 do
		local x2 = pgon[i]
		local y2 = pgon[i+1]
		next_quad = getQuad(tx,ty,x2,y2)
		local diff = next_quad - cur_quad

		if (diff == 2) or (diff == -2) then
			if (x2 - (((y2 - ty) * (x1 - x2)) / (y1 - y2))) < tx then
				diff = -diff
			end
		elseif diff == 3 then
			diff = -1
		elseif diff == -3 then
			diff = 1
		end

		total = total + diff
		cur_quad = next_quad
		x1 = x2
		y1 = y2
	end
	
	return (math.abs(total)==4)
end

function getQuad(axis_x,axis_y,vert_x,vert_y)
	if vert_x < axis_x then
		if vert_y < axis_y then
			return 1
		else
			return 4
		end
	else
		if vert_y < axis_y then
			return 2
		else
			return 3
		end	
	end
end

Sample:

function love.load()
	poly = {69,119,371,39,724,140,751,491,572,222,420,163,283,232,236,338,399,401,540,446,371,508,195,503,96,327}
	color = {255,255,255}
end

function love.update(dt)
	if pointInPolygon(poly, love.mouse.getX(), love.mouse.getY()) then
		color = {0,255,0}
	else
		color = {255,255,255}
	end
end

function love.draw()
	if #poly >= 6 then
		love.graphics.setColor(color)
		love.graphics.polygon("line",poly)
	end
end

-- Add functions pointInPolygon and getQuad here