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

Max

  • Full Member
  • ***
  • Posts: 212
    • 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: 1172
    • 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: 212
    • 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) [Select]
  elseif entity_type == "switch" then
    --activate the switch you hit if it's solid or arrow-type
    local switch = entity
    local sprite = switch:get_sprite()
    --check if the switch's sprite is the right type for activating
    if flying and sprite ~= nil and
    (sprite:get_animation_set() == "entities/switch_solid" or "entities/switch_lever_1" or "entities/switch_arrow") then
 
      --if it's off, turn it on. Or vice-versa.
      if not switch:is_activated() then
        sol.audio.play_sound("switch")
        switch:set_activated(true)
        switch:on_activated()
      else
        sol.audio.play_sound("switch")
        switch:set_activated(false)
        switch:on_inactivated()
      end