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 02:02:15 |
👁️ 阅读: 15
要实现显示距离第二天还有多久的倒计时,你需要计算当前时间到第二天0点的剩余秒数,然后使用`GUI:Text_COUNTDOWN`函数来显示这个倒计时。
根据浮生梦老师前端课程内容,`GUI:Text_COUNTDOWN`函数可以用于显示倒计时,但你需要先计算正确的剩余时间。这里有一个关键点:你需要获取服务器时间来计算,而不是本地时间,以确保所有玩家看到的时间一致。
以下是修改后的代码:
```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:----------------1", 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)
-- 在按钮正下方添加倒计时文本
local timeText = GUI:Text_Create(Top_node_obj, "timeText_" .. v.but_id, v.x, v.y - 46 - 10, 16, "#FF0000", "")
GUI:setAnchorPoint(timeText, 0.5, 0.5)
-- 计算距离第二天0点的剩余时间
local function updateCountdown()
-- 获取当前服务器时间戳
local currentTime = SL:GetMetaValue("SERVER_TIME")
-- 计算当前时间的日期(去掉时分秒)
local currentDate = os.date("*t", currentTime)
currentDate.hour = 0
currentDate.min = 0
currentDate.sec = 0
local todayZero = os.time(currentDate)
-- 计算明天0点的时间戳
local tomorrowZero = todayZero + 24 * 60 * 60
-- 计算剩余秒数
local remainingSeconds = tomorrowZero - currentTime
-- 设置倒计时
GUI:Text_COUNTDOWN(timeText, remainingSeconds, nil, 0)
end
-- 立即更新一次
updateCountdown()
-- 每秒更新一次(确保倒计时准确)
SL:schedule(timeText, function()
updateCountdown()
end, 1)
end
end, 0.2)
end
return MainButton
```
**代码说明:**
1. **获取服务器时间**:使用`SL:GetMetaValue("SERVER_TIME")`获取当前服务器时间戳,确保所有玩家时间一致。
2. **计算今天0点**:通过`os.date("*t", currentTime)`获取时间表,然后将时分秒设为0,再通过`os.time()`转换回时间戳。
3. **计算明天0点**:今天0点时间戳加上24小时(86400秒)。
4. **计算剩余时间**:明天0点时间戳减去当前时间戳,得到剩余秒数。
5. **设置倒计时**:使用`GUI:Text_COUNTDOWN(timeText, remainingSeconds, nil, 0)`显示倒计时,格式为"xx时xx分xx秒"。
6. **定时更新**:使用`SL:schedule`每秒更新一次倒计时,确保显示准确。
这样修改后,你的按钮下方就会显示距离第二天0点还有多长时间的倒计时了。如果倒计时结束,它会自动重置到新的一天。
← 返回问答库