i have just invented the button (also fixed controls:consume)

This commit is contained in:
PeaAshMeter 2025-09-04 00:23:15 +03:00
parent 8c1166216c
commit bd6ec87dd0
3 changed files with 24 additions and 15 deletions

View File

@ -49,9 +49,11 @@ function controls:cache()
end
--- marks a control consumed for the current frame
---
--- the control will no longer be considered active
--- @param key string
function controls:consume(key)
cachedKeys[key] = true
currentKeys[key] = nil
end

View File

@ -1,3 +1,5 @@
local controls = require "lib.controls"
---@class UIConstraints
---@field min_w number
---@field min_h number
@ -107,6 +109,20 @@ function Element:draw()
end
end
--- calls the callback if clicked inside own bounding box (rectangular)
--- @param callback function
function Element:onTap(callback)
local mx, my = love.mouse.getPosition()
if mx > self.origin.x and mx < self.origin.x + self.size.x
and my > self.origin.y and my < self.origin.y + self.size.y
then
if controls:isJustPressed("select") then
controls:consume("select")
callback()
end
end
end
-- =============== SingleChild / MultiChild базовые ===============
--- @class SingleChildElement: Element

View File

@ -1,29 +1,20 @@
local Vec3 = require "lib.utils.vec3"
local ui = require "lib.ui.core"
local controls = require "lib.controls"
--- @type Rectangle
local ReactiveRectangle = ui.Rectangle {
size = Vec3 { 100, 100 },
color = { 1, 0, 0 },
state = { tick = 0 }
state = { active = false }
}
function ReactiveRectangle:update(dt)
getmetatable(self):update(dt)
local mx, my = love.mouse.getPosition()
if mx > self.origin.x and mx < self.origin.x + self.size.x
and my > self.origin.y and my < self.origin.y + self.size.y
then
if controls:isJustPressed("select") then
controls:consume("select")
end
self.color = { 0, 1, 0 }
else
self.color = { 1, 0, 0 }
end
self.state.tick = self.state.tick + 1
self:onTap(function()
self.state.active = not self.state.active
self.color = self.state.active and { 0, 1, 0 } or { 1, 0, 0 }
end)
end
local Layout = ui.Root {