From bd6ec87dd0a3a587eb66f1c229bae922e82193ed Mon Sep 17 00:00:00 2001 From: PeaAshMeter Date: Thu, 4 Sep 2025 00:23:15 +0300 Subject: [PATCH] i have just invented the button (also fixed controls:consume) --- lib/controls.lua | 2 ++ lib/ui/core.lua | 16 ++++++++++++++++ lib/ui/layout.lua | 21 ++++++--------------- 3 files changed, 24 insertions(+), 15 deletions(-) diff --git a/lib/controls.lua b/lib/controls.lua index 50de9ab..5f283c5 100644 --- a/lib/controls.lua +++ b/lib/controls.lua @@ -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 diff --git a/lib/ui/core.lua b/lib/ui/core.lua index 3fe6fe5..153f3e2 100644 --- a/lib/ui/core.lua +++ b/lib/ui/core.lua @@ -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 diff --git a/lib/ui/layout.lua b/lib/ui/layout.lua index 537d14b..a54f9a0 100644 --- a/lib/ui/layout.lua +++ b/lib/ui/layout.lua @@ -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 {