我正在编写一个应用程序,当你点击一个按钮时,它会增加倒数计时器剩余的时间,并且还会增加计数器上的数字,显示你已经完成了多少次点击。我的问题是,当两个数字相等时,倒计时停止,数字和计数器成为同义词。我需要改变什么/我做错了什么?
-- Create Button
local blueButton = display.newCircle (160,240,45)
blueButton:setFillColor(0,.5,1)
-- Create Tap-counter
local number = 0
local textField = display.newText(number, 160, 30, native.systemFont, 52)
-- Create Countdown Timer
local count = 20
local textCount = display.newText(count, 160, 70, native.systemFont, 52)
textCount:setFillColor(0,1,.25)
-- Create countdown function
local function countDown()
count = count - 1
textCount:removeSelf()
textCount = display.newText(count, 160, 70, native.systemFont, 52)
textCount:setFillColor(0,1,.25)
end
-- Create tap function
local function buttonTap(event)
number = number + 1
textField:removeSelf()
textField = display.newText(number, 160, 30, native.systemFont, 52)
count = count + 1
textCount:removeSelf()
textCount = display.newText(count, 160, 70, native.systemFont, 52)
textCount:setFillColor(0,1,.25)
end
-- Tapping button calls tap function
blueButton:addEventListener("tap", buttonTap)
-- countdown every second
timer.performWithDelay(1000, countDown, count)
答案 0 :(得分:2)
如果要将倒数计为0,则需要设置无限次的计时器迭代次数。这就是为什么我使用-1作为计时器的最后一个参数。
其次,每次迭代后都不需要创建新的文本对象。只需更改其上的文字即可。
有关您在documentation中找到的计时器的详细信息。
尝试
-- Create Button
local blueButton = display.newCircle (160,240,45)
blueButton:setFillColor(0,.5,1)
-- Create Tap-counter
local number = 0
local textField = display.newText(number, 160, 30, native.systemFont, 52)
-- Create Countdown Timer
local count = 20
local textCount = display.newText(count, 160, 70, native.systemFont, 52)
textCount:setFillColor(0,1,.25)
local myTimer
-- Create countdown function
local function countDown()
count = count - 1
textCount.text = count
if ( count < 1 ) then -- so count = 0 if true
timer.cancel( myTimer )
end
end
-- Create tap function
local function buttonTap(event)
number = number + 1
textField.text = number
count = count + 1
textCount.text = count
end
-- Tapping button calls tap function
blueButton:addEventListener("tap", buttonTap)
-- countdown every second
myTimer = timer.performWithDelay(1000, countDown, -1)