local MainButton = {}
MainButton.cfg = {
{ but_id = "id1 ", x = 230, y = -270, but_img = "res/public/996kf_red.png", cmd = { 3100, 1 } }, --GM功能
}
function MainButton:main()
SL:ScheduleOnce(function()
local parent = GUI:Attach_LeftTop
🤖 回答引擎: 前端Lua |
🕒 时间: 2026-03-09 01:57:06 |
👁️ 阅读: 19
要在第一个按钮正下方添加倒计时显示,我们可以参考浮生梦老师前端课程中的倒计时实现方式。以下是修改后的代码:
```lua
local MainButton = {}
MainButton.cfg = {
{ but_id = "id1", x = 230, y = -270, but_img = "res/public/996kf_red.png", cmd = { 3100, 1 } }, --GM功能
}
function MainButton:main()
SL:ScheduleOnce(function()
local parent = GUI:Attach_LeftTop()
SL:print("parent:-----------------", parent)
if GUI:Win_IsNull(parent) then
SL:print("parent为空")
return
end
-- 检查并移除旧节点
if GUI:getChildByName(parent, "node_rightSide_1") then
local oldNode = GUI:getChildByName(parent, "node_rightSide_1")
GUI:removeFromParent(oldNode)
SL:print("删除了旧节点")
end
-- 创建新节点
local Top_node_obj = GUI:Widget_Create(parent, "node_rightSide_1", 0, 0, 0, 0)
if GUI:Win_IsNull(Top_node_obj) then
SL:print("创建节点失败")
return
end
for _, v in pairs(MainButton.cfg) do
-- 创建按钮
local but_switch = GUI:Button_Create(Top_node_obj, "switch", v.x, v.y, v.but_img)
SL:print("点击了" .. v.but_id .. "按钮", v.x, v.y)
GUI:addOnClickEvent(but_switch, function()
SL:print("点击了" .. v.but_id .. "按钮")
end)
-- 在按钮正下方添加倒计时文本
-- 按钮高度假设为46(根据课程案例),设置倒计时在按钮下方10像素位置
local timeText = GUI:Text_Create(Top_node_obj, "timeText_" .. v.but_id, v.x, v.y - 46 - 10, 16, "#FF0000", "10")
GUI:setAnchorPoint(timeText, 0.5, 0.5)
-- 倒计时回调函数
local function callback()
-- 这里假设有一个结束时间,你可以根据需要修改
local endTime = SL:GetMetaValue("SERVER_TIME") + 10 -- 10秒后结束
local remaining = endTime - SL:GetMetaValue("SERVER_TIME")
GUI:Text_setString(timeText, tostring(remaining))
if remaining <= 0 then
GUI:stopAllActions(timeText)
GUI:Text_setString(timeText, "")
-- 可以添加倒计时结束的回调
end
end
-- 启动定时器,每秒更新一次
SL:schedule(timeText, callback, 1)
callback() -- 立即执行一次
end
end, 0.2)
end
return MainButton
```
**代码说明:**
1. **创建倒计时文本**:使用`GUI:Text_Create`在每个按钮下方创建倒计时显示
- 位置计算:`v.y - 46 - 10` 表示在按钮下方46像素(按钮高度)再往下10像素
- 文本ID使用唯一标识:`"timeText_" .. v.but_id`
2. **设置锚点**:`GUI:setAnchorPoint(timeText, 0.5, 0.5)`让文本居中显示
3. **倒计时逻辑**:
- 使用`SL:GetMetaValue("SERVER_TIME")`获取服务器时间
- 计算剩余时间并更新文本显示
- 倒计时结束后清空文本并停止所有动作
4. **定时器**:使用`SL:schedule(timeText, callback, 1)`每秒更新一次倒计时
**注意事项:**
- 按钮高度46像素是根据课程案例中的`GUI:setContentSize(iconBtn, 46, 46)`设置的
- 如果按钮实际高度不同,需要调整`v.y - 46 - 10`中的46为实际高度
- 倒计时结束时间需要根据你的实际需求设置,这里示例为10秒后结束
- 记得在适当的时候清理定时器,避免内存泄漏
这样就在每个按钮正下方添加了一个倒计时显示,会从10开始倒数到0。
← 返回问答库