- Select manual -

Trigger

This example shows how a physics trigger is used to trigger an event. In this case the bunny sprite is disabled and enabled.

trigger

The setup consists of two game objects.

trigger
The invisible trigger. Contains:
  • A Collision object component. The Type is set to TRIGGER. A box Shape is added to the componens.
bunny
The bunny. Contains:
  • A Sprite component with the bunny image.
  • A Collision object component. It has Type set to DYNAMIC. A sphere Shape matching the sprite image is added to the componens.
  • A Script component that animates the bunny’s position and reacts to physics messages when interacting with the trigger.

bunny.script

function init(self)
    local pos = go.get_position() 
    go.animate(".", "position.x", go.PLAYBACK_LOOP_PINGPONG, pos.x + 600, go.EASING_INOUTSINE, 6)
end

function on_message(self, message_id, message, sender)
    if message_id == hash("trigger_response") then 
        if message.enter then 
            msg.post("#sprite", "disable") 
        else
            msg.post("#sprite", "enable") 
        end
    end
end
  1. Get the current position, then animate the position’s x component looping in a ping-pong manner against an offset of 600.
  2. The physics engine has detected that this game object contains collision object components that have collided with a trigger.
  3. The message data table contains a field enter that is set to true when the trigger event signals that the trigger shape was entered. On exiting the trigger, this field is false.
  4. Disable the sprite when the trigger is entered
  5. Enable the sprite again on exit.

If you want to play with these examples, you can get the project on Github.

Do you want to see more examples? Why not write a few yourself and submit a pull request? We love contributions.

Contribute