Guest User

Untitled

a guest
Jan 21st, 2019
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. local pivot = {
  2. x = 200,
  3. y = 200,
  4. w = 100,
  5. h = 150,
  6. }
  7.  
  8. local rect = {
  9. x = 0,
  10. y = 0,
  11. w = 150,
  12. h = 100,
  13. }
  14.  
  15. function draw_rect(rect)
  16. love.graphics.rectangle("line", rect.x, rect.y, rect.w, rect.h);
  17. end
  18.  
  19. function rect_overlap(rect1, rect2)
  20. return rect1.x + rect1.w >= rect2.x
  21. and rect2.x + rect2.w >= rect1.x
  22. and rect2.y + rect2.h >= rect1.y
  23. and rect1.y + rect1.h >= rect2.y
  24. end
  25.  
  26. function rect_center(rect)
  27. return {
  28. x = rect.x + rect.w * 0.5,
  29. y = rect.y + rect.h * 0.5,
  30. }
  31. end
  32.  
  33. function sign(x)
  34. return x / math.abs(x)
  35. end
  36.  
  37. function rect_impulse(r1, r2)
  38. local c1 = rect_center(r1)
  39. local c2 = rect_center(r2)
  40. local d = math.min(c1.x, c2.x) + math.abs(c1.x - c2.x) * 0.5
  41.  
  42. if c1.x < c2.x then
  43. return
  44. {
  45. x = d - r1.w,
  46. y = r1.y,
  47. w = r1.w,
  48. h = r1.h,
  49. },
  50. {
  51. x = d,
  52. y = r2.y,
  53. w = r2.w,
  54. h = r2.h,
  55. }
  56. else
  57. return
  58. {
  59. x = d,
  60. y = r1.y,
  61. w = r1.w,
  62. h = r1.h,
  63. },
  64. {
  65. x = d - r2.w,
  66. y = r2.y,
  67. w = r2.w,
  68. h = r2.h,
  69. }
  70. end
  71. end
  72.  
  73. function rect_snap(p, r)
  74. local pc = rect_center(p)
  75. local rc = rect_center(r)
  76.  
  77. local x = pc.x + sign(rc.x - pc.x) * (p.w + r.w) * 0.5 - r.w * 0.5
  78. local y = pc.y + sign(rc.y - pc.y) * (p.h + r.h) * 0.5 - r.h * 0.5
  79.  
  80. if math.abs(x - rc.x) < math.abs(y - rc.y) then
  81. return {
  82. x = x,
  83. y = r.y,
  84. w = r.w,
  85. h = r.h
  86. }
  87. else
  88. return {
  89. x = r.x,
  90. y = y,
  91. w = r.w,
  92. h = r.h
  93. }
  94. end
  95. end
  96.  
  97. function love.draw()
  98. love.graphics.setColor(255, 255, 255, 255)
  99. draw_rect(pivot)
  100. draw_rect(rect)
  101. end
  102.  
  103. function love.update(dt)
  104. rect.x = love.mouse.getX() - rect.w * 0.5
  105. rect.y = love.mouse.getY() - rect.h * 0.5
  106.  
  107. if rect_overlap(pivot, rect) then
  108. pivot, rect = rect_impulse(pivot, rect)
  109. end
  110. end
Add Comment
Please, Sign In to add comment