Problem with timer

Started by Starlock, May 29, 2017, 09:48:25 PM

Previous topic - Next topic
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) Select

  if torch_light:get_sprite():get_animation() == "lit" or torch_light_2:get_sprite():get_animation() == "lit" or
  torch_light_3:get_sprite():get_animation() == "lit" then
      map:set_entities_enabled("torchbridge", true)
        sol.timer.start(3500, function()

          map:set_entities_enabled("torchbridge", false)
torch_light:get_sprite():set_animation("unlit")
torch_light_2:get_sprite():set_animation("unlit")
torch_light_3:get_sprite():set_animation("unlit")
      end)
    end

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.

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