Author Topic: Activating a switch from a script?  (Read 192 times)

Max

  • Full Member
  • ***
  • Posts: 101
    • View Profile
Activating a switch from a script?
« on: February 27, 2018, 02:15:30 am »
Hello!

I've been looking over the Solarus Team's bow/arrows script, which is super cool, and developed a script using it that shoots fire arrows. But one problem I'm encountering is that it uses switch:set-activated() to allow arrows to interact with switches. However, this method doesn't trigger the switch:on_activated() event.

I've found a workaround with setting a timer that checks to see if the switch has been activated ever 100ms or so and acts accordingly, but is there a better way to do this? Is there a way to trigger the event from a script?

Thanks!

Christopho

  • Administrator
  • Hero Member
  • *****
  • Posts: 1103
    • View Profile
Re: Activating a switch from a script?
« Reply #1 on: February 27, 2018, 10:50:32 am »
Hi,
Events are regular functions, so you can always call switch:on_activated() yourself if you want, after switch:set_activated().

Max

  • Full Member
  • ***
  • Posts: 101
    • View Profile
Re: Activating a switch from a script?
« Reply #2 on: February 27, 2018, 03:59:13 pm »
Oh! I think I get it! Yeah, I thought events were special functions that were only called when certain requirements were met.

So I think my code should look like this, which seems to work:


Code: Lua
  1.   elseif entity_type == "switch" then
  2.     --activate the switch you hit if it's solid or arrow-type
  3.     local switch = entity
  4.     local sprite = switch:get_sprite()
  5.     --check if the switch's sprite is the right type for activating
  6.     if flying and sprite ~= nil and
  7.     (sprite:get_animation_set() == "entities/switch_solid" or "entities/switch_lever_1" or "entities/switch_arrow") then
  8.  
  9.       --if it's off, turn it on. Or vice-versa.
  10.       if not switch:is_activated() then
  11.         sol.audio.play_sound("switch")
  12.         switch:set_activated(true)
  13.         switch:on_activated()
  14.       else
  15.         sol.audio.play_sound("switch")
  16.         switch:set_activated(false)
  17.         switch:on_inactivated()
  18.       end