Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local pivot = {
- x = 200,
- y = 200,
- w = 100,
- h = 150,
- }
- local rect = {
- x = 0,
- y = 0,
- w = 150,
- h = 100,
- }
- function draw_rect(rect)
- love.graphics.rectangle("line", rect.x, rect.y, rect.w, rect.h);
- end
- function rect_overlap(rect1, rect2)
- return rect1.x + rect1.w >= rect2.x
- and rect2.x + rect2.w >= rect1.x
- and rect2.y + rect2.h >= rect1.y
- and rect1.y + rect1.h >= rect2.y
- end
- function rect_center(rect)
- return {
- x = rect.x + rect.w * 0.5,
- y = rect.y + rect.h * 0.5,
- }
- end
- function sign(x)
- return x / math.abs(x)
- end
- function rect_impulse(r1, r2)
- local c1 = rect_center(r1)
- local c2 = rect_center(r2)
- local d = math.min(c1.x, c2.x) + math.abs(c1.x - c2.x) * 0.5
- if c1.x < c2.x then
- return
- {
- x = d - r1.w,
- y = r1.y,
- w = r1.w,
- h = r1.h,
- },
- {
- x = d,
- y = r2.y,
- w = r2.w,
- h = r2.h,
- }
- else
- return
- {
- x = d,
- y = r1.y,
- w = r1.w,
- h = r1.h,
- },
- {
- x = d - r2.w,
- y = r2.y,
- w = r2.w,
- h = r2.h,
- }
- end
- end
- function rect_snap(p, r)
- local pc = rect_center(p)
- local rc = rect_center(r)
- local x = pc.x + sign(rc.x - pc.x) * (p.w + r.w) * 0.5 - r.w * 0.5
- local y = pc.y + sign(rc.y - pc.y) * (p.h + r.h) * 0.5 - r.h * 0.5
- if math.abs(x - rc.x) < math.abs(y - rc.y) then
- return {
- x = x,
- y = r.y,
- w = r.w,
- h = r.h
- }
- else
- return {
- x = r.x,
- y = y,
- w = r.w,
- h = r.h
- }
- end
- end
- function love.draw()
- love.graphics.setColor(255, 255, 255, 255)
- draw_rect(pivot)
- draw_rect(rect)
- end
- function love.update(dt)
- rect.x = love.mouse.getX() - rect.w * 0.5
- rect.y = love.mouse.getY() - rect.h * 0.5
- if rect_overlap(pivot, rect) then
- pivot, rect = rect_impulse(pivot, rect)
- end
- end
Add Comment
Please, Sign In to add comment