I am using an timer to update the score in my game but dont know how to update the created timer, i think i am creating a new timer now everytime i am sending an message:
In main i have:
function update(self, dt)
if self.level == 1 then
msg.post("ui#ui", "level_1")
end
end
And when in my ui script i have:
function on_message(self, message_id, message, sender)
if message_id == hash("level_1") then
self.scoreSpeed = 1
score(self.scoreSpeed)
print("level1")
print(self.scoreSpeed)
end
end
function score(score_speed)
local id = delay.repeating(score_speed, function(self, id)
self.score = self.score + 1
end)
end
I have tested the built in timer too but as i said i think i am just creating new timers everytime i get the message which is every update.
Is where a way to update a running timer? and how do i do it?
I dont get it to work, i remove local so i could cancel the timer outside of the function but now it wont start a new timer, what am i doing wrong? The scoreSpeed gets changed but no new timer is being created.
function init(self)
self.restartbutton = gui.get_node("restartbutton")
self.playbutton = gui.get_node("playbutton")
self.pixels = gui.get_node("pixels")
self.score = 0
self.scoreSpeed = 1
print(pixels)
gui.set_enabled(self.restartbutton, false)
gui.set_enabled(self.playbutton, false)
score(self.scoreSpeed)
end
function update(self, dt)
if self.score == 5 then
self.scoreSpeed = 0.1
timer.cancel(id)
score(self.scoreSpeed)
print(self.scoreSpeed)
end
gui.set_text(self.pixels, self.score)
end
function score(score_speed)
id = timer.delay(score_speed, true, function(self, id)
self.score = self.score + 1
end)
end
function update(self, dt)
if self.score == 5 then
self.scoreSpeed = 0.1
timer.cancel(id)
When the score reaches 5 you will start cancelling the timer every frame which is probably not what you intended?
Why not check the score and cancel the timer from within the timer callback itself. Also, make sure to use local or self scoped variables and functions like @tacklemcclean suggested. Something like this:
local function start_score_timer(self)
if self.timer_id then
print("Cancelling existing timer")
timer.cancel(self.timer_id)
end
self.timer_id = timer.delay(self.scoreSpeed, true, function(self, id)
self.score = self.score + 1
print(socket.gettime(), self.score)
if self.score == 5 then
print("Score is 5, changing score speed")
self.scoreSpeed = 0.1
start_score_timer(self)
end
end)
end
function init(self)
self.score = 0
self.scoreSpeed = 1
start_score_timer(self)
end