Author Topic: Problem with timer  (Read 225 times)

Starlock

  • Jr. Member
  • **
  • Posts: 81
    • View Profile
Problem with timer
« on: May 29, 2017, 09:48:25 pm »
I'm trying to make a bridge that appears when at least one of three torches is lit. I'm having trouble making the timer work properly, since once the timer finishes there's a delay before it can activate again so you can't light the torch again in that time frame. Is there a way to make the timer instantly be activatable again after it finishes?

Here is my code(It is part of function map:on_update()):
Code: Lua
  1.   if torch_light:get_sprite():get_animation() == "lit" or torch_light_2:get_sprite():get_animation() == "lit" or
  2.   torch_light_3:get_sprite():get_animation() == "lit" then
  3.       map:set_entities_enabled("torchbridge", true)
  4.         sol.timer.start(3500, function()
  5.  
  6.           map:set_entities_enabled("torchbridge", false)
  7. torch_light:get_sprite():set_animation("unlit")
  8. torch_light_2:get_sprite():set_animation("unlit")
  9. torch_light_3:get_sprite():set_animation("unlit")
  10.       end)
  11.     end

llamazing

  • Jr. Member
  • **
  • Posts: 73
    • View Profile
Re: Problem with timer
« Reply #1 on: May 29, 2017, 10:41:33 pm »
I think your problem is that you are using map:on_update(), which gets called every cycle. With the way you have things set up, a new timer is getting created every cycle as long as at least one torch is lit. Try adding a print statement at line 5, and you'll probably see a bunch of timers getting created. So what's happening is after 3.5 seconds the "first" timer expires and un-unlights all the torches, but then every cycle all the other timers continue to expire and also un-light all the torches. So then you have to wait another 3.5 seconds for the "last" timer to expire before you can light the torches again.

A better way to do it is to use sprite:on_animation_changed(animation) instead of map:on_update(). That way the function doesn't get called every cycle.

And if you are doing what I think you are doing, you'll probably want three separate timers. It can be done with one timer (that gets restarted each time a torch is lit perhaps?), but that would also mean that all the torches will become unlit simultaneously.

MetalZelda

  • Hero Member
  • *****
  • Posts: 508
    • View Profile
Re: Problem with timer
« Reply #2 on: May 29, 2017, 11:31:29 pm »
I don't really understand the on_update() usage there

what you can do is using map:get_entities("")
http://www.solarus-games.org/doc/latest/lua_api_map.html#lua_api_map_get_entities

This way, this should work