This is typically done via message passing, at least if it’s from a gui component like a button to a gameobject. Imagine this setup with one gui containing a button and a game object for the player:
The gui looks like this:
The gui has the following script:
function init(self)
msg.post(".", "acquire_input_focus")
end
function on_input(self, action_id, action)
if action_id == hash("touch") and action.released then
if gui.pick_node(gui.get_node("jump_button"), action.x, action.y) then
msg.post("player", "jump")
end
end
end
- The script acquires input focus (ie will get input events from the engine).
- The script checks for a touch action (mapped in input bindings). In my case for left mouse button (which will auto bind for touch events on mobile as well)
- If a touch action is detected and the touch/click was released (ie finger leaves screen or mouse button) then we proceed to check if the finger/mouse was within the bounds of the button box node named “jump_button”
- If the touch/click was within the bounds of the button we send a message to a game object with id “player”. The message we send has the id “jump”.
Message passing can be used to send a message to any part of your application from anywhere else. It’s very powerful and the typical use-case is as easy as above, but for sending messages to other systems you need to understand the addressing system used in Defold. You can read more about this in the Message Passing manual.
The receiver of the “jump” message is the player game object. The player has a script attached which will take care of the message:
function on_message(self, message_id, message, sender)
if message_id == hash("jump") then
local to = go.get_position().y + 20
go.animate(".", "position.y", go.PLAYBACK_ONCE_PINGPONG, to, go.EASING_INOUTQUAD, 1)
end
end
Here we detect the message (note messages are hashes for performance reasons) and we let the engine animate the game object using go.animate().