用计时器更改文本

时间:2017-04-26 10:12:40

标签: lua corona

我想在几秒钟后更改文本对象的字符串。这是代码:

  if scoretoShow then
aAscoretext = display.newText( scoretoShow.."/8", 200, 200, "Comic Sans MS", 30)
else
aAscoretext = display.newText( "0/8", 200, 200, "Comic Sans MS", 30)
end
aAscoretext:setFillColor( 0.4 )
aAscoretext.x = Letterbackground.x
aAscoretext.y = Letterbackground.y + Letterbackground.width/3


   if type(scoreChange) == "number" then
for f = 0, scoreChange, 1 do
    print("f")
        print(f)

timer.performWithDelay( timeforChange-(f*(timeforChange/scoreChange)), 
function()
 aAscoretext.text = "HELLO!"
Letterbackground:setFillColor( gradients[newScore-f+1] )
audio.play(Wobble)
end)

但是,如果我将aAscoretext.text = "HELLO!"置于print(f)之下,那么它可以正常工作。

谢谢。

1 个答案:

答案 0 :(得分:0)

timer.performWithDay()循环中对for的所有调用可能都没有按预期执行。我发现如果需要更改中的另一个步骤,那么在延迟一段时间后,更改TextObject中更改text属性的侦听器会更容易再次调用自身。

这将说明我的意思。假设您有一个显示分数的TextObject score和两个变量currentScorenewScore newScore > currentScore,其中两个都是整数值。如果您希望分数显示从currentScore“计数”到newScore,您可以这样做:

local currentScore = 0 

--
-- Call this function when the score needs to change
--
local function newScoreToDisplay( newScore )    

    local countingInterval = 100 -- we want to add 1 to the displayed score every 100 ms

    local function adjustScoreDisplay( event )

       if currentScore < newScore then
           currentScore = currentScore + 1
           score.text = tostring( currentScore ) -- score is a Corona TextObject
           timer.performWithDelay( countingInterval, adjustScoreDisplay )
       end
    end

    -- First call to adjustScore() if score really needs adjusting
    if currentScore < newScore then
        timer.performWithDelay( 0, adjustScore ) --make the first change immediately
    end
end