Possible optimizations:
move some code to love.keypressed, love.mousemoved, love.mousereleased
store variables out of rectangles
Code: Select all
-- License CC0 (Creative Commons license) (c) darkfrei, 2023
Width, Height = love.graphics.getDimensions( )
function love.load()
Rectangles = {}
for i = 1, 10 do
local w = love.math.random (Width/8)+1/8*Width
local h = love.math.random (Height/8)+1/16*Height
local x = love.math.random (Width-w)
local y = love.math.random (Height-h)
local rectangle = {x=x,y=y,w=w,h=h,dx=0,dy=0}
table.insert(Rectangles, rectangle)
end
end
local function isOn (mx, my, rect)
return mx > rect.x and mx < rect.x + rect.w and my > rect.y and my < rect.y + rect.h or false
end
function love.update(dt)
local mx, my = love.mouse.getPosition()
local mouseDown = love.mouse.isDown(1)
local hovered = false
for i = 1, #Rectangles, 1 do
local rect = Rectangles[i]
if not hovered and isOn (mx, my, rect) then
rect.hovered = true
hovered = rect
else
rect.hovered = false
end
if not mouseDown then
rect.taken = false
end
end
if hovered and mouseDown then
if hovered.taken then
hovered.x = mx-hovered.dx
hovered.y = my-hovered.dy
else
hovered.taken = true
hovered.dx = mx-hovered.x
hovered.dy = my-hovered.y
end
end
end
function love.draw()
-- draw backwards!
for i = #Rectangles, 1, -1 do
local rect = Rectangles[i]
if rect.taken then
love.graphics.setColor (0.5,0.5,0.5)
love.graphics.rectangle('fill', rect.x, rect.y, rect.w, rect.h)
love.graphics.setLineWidth(3)
love.graphics.setColor (0,1,0)
love.graphics.rectangle('line', rect.x, rect.y, rect.w, rect.h)
elseif rect.hovered then
love.graphics.setColor (0.5,0.5,0.5)
love.graphics.rectangle('fill', rect.x, rect.y, rect.w, rect.h)
love.graphics.setLineWidth(2)
love.graphics.setColor (1,1,0)
love.graphics.rectangle('line', rect.x, rect.y, rect.w, rect.h)
else -- not active
love.graphics.setColor (0.5,0.5,0.5)
love.graphics.rectangle('fill', rect.x, rect.y, rect.w, rect.h)
love.graphics.setLineWidth(1)
love.graphics.setColor (1,1,1)
love.graphics.rectangle('line', rect.x, rect.y, rect.w, rect.h)
end
love.graphics.print ('x:'..rect.x..' y:'..rect.y, rect.x, rect.y)
love.graphics.print ('dx:'..rect.dx..' dy:'..rect.dy, rect.x, rect.y+14)
end
end