Can you please help me to make the function to get the push-vector to move the rectangle from the line?
Partially works:
Code: Select all
local function signDistancePointToLine (px, py, lineX1, lineY1, lineX2, lineY2)
local dx, dy = lineX2 - lineX1, lineY2 - lineY1
local len = math.sqrt(dx * dx + dy * dy)
local dist = ((lineY1 - py) * dx - (lineX1 - px) * dy) / len
dx, dy = dx/len, dy/len
return {dist = dist, dx=dx, dy=dy, px=px, py=py}
end
local function pushRectangleOutOfLine(rectX, rectY, rectWidth, rectHeight, lineX1, lineY1, lineX2, lineY2)
local x1, y1 = rectX, rectY
local x3, y3 = rectX+rectWidth, rectY+rectHeight
local x2, y2 = x3, y1
local x4, y4 = x1, y3
local distances = {
signDistancePointToLine (x1, y1, lineX1, lineY1, lineX2, lineY2),
signDistancePointToLine (x2, y2, lineX1, lineY1, lineX2, lineY2),
signDistancePointToLine (x3, y3, lineX1, lineY1, lineX2, lineY2),
signDistancePointToLine (x4, y4, lineX1, lineY1, lineX2, lineY2),
}
local posiN, negaN = {}, {}
for i, d in ipairs (distances) do
if d.dist > 0 then
table.insert (posiN, d)
else
table.insert (negaN, d)
end
end
local dist, dx, dy = 0
local px, py
if #posiN == 1 then
dist, dx, dy = posiN[1].dist, posiN[1].dx, posiN[1].dy
px, py = posiN[1].px, posiN[1].py
elseif #negaN == 1 then
dist, dx, dy = negaN[1].dist, negaN[1].dx, negaN[1].dy
px, py = negaN[1].px, negaN[1].py
elseif #posiN > 1 then
dist, dx, dy = posiN[1].dist, posiN[1].dx, posiN[1].dy
px, py = posiN[1].px, posiN[1].py
else
dist, dx, dy = negaN[1].dist, negaN[1].dx, negaN[1].dy
px, py = negaN[1].px, negaN[1].py
end
local pushVecX, pushVecY = -dist*dy, dist*dx
print (pushVecX, pushVecY)
return pushVecX, pushVecY, px, py
end
function love.load()
rectX, rectY, rectWidth, rectHeight = 100, 100, 200, 200
lineX1, lineY1, lineX2, lineY2 = 50, 20, 200, 400
pushVecX, pushVecY, PX, PY = pushRectangleOutOfLine(rectX, rectY, rectWidth, rectHeight, lineX1, lineY1, lineX2, lineY2)
end
function love.draw()
love.graphics.setColor(1, 1, 1)
love.graphics.rectangle("fill", rectX, rectY, rectWidth, rectHeight)
love.graphics.setColor(1, 0, 0)
love.graphics.line(lineX1, lineY1, lineX2, lineY2)
love.graphics.setColor(0, 1, 0)
love.graphics.line(PX, PY, PX + pushVecX, PY + pushVecY)
love.graphics.setColor(1, 0, 0)
love.graphics.rectangle("line", rectX+pushVecX, rectY+pushVecY, rectWidth, rectHeight)
end
function love.keypressed(k)
if k == 'z' then
lineX1, lineY1 = love.mouse.getPosition()
pushVecX, pushVecY, PX, PY = pushRectangleOutOfLine(rectX, rectY, rectWidth, rectHeight, lineX1, lineY1, lineX2, lineY2)
elseif k == 'x' then
lineX2, lineY2 = love.mouse.getPosition()
pushVecX, pushVecY, PX, PY = pushRectangleOutOfLine(rectX, rectY, rectWidth, rectHeight, lineX1, lineY1, lineX2, lineY2)
end
if k == 'escape' then
love.event.quit()
end
end
But I've got the error on two corners cutting.
Press z and x to change the point: