defold-input

Simplify input related operations such as gesture detection, input mapping and clicking/dragging game objects

View the Project on GitHub

Cursor

Use the cursor script to simplify user interaction such as clicking and dragging of game objects.

Usage

Attach the cursor.script to a game object that should act as a cursor. The game object must have either a kinematic or trigger collision object with a group and mask that matches other collision objects that should be able to interact with the cursor.

IMPORTANT: You must make sure to configure the cursor.script action_id field (see below) to match the binding you have in your input bindings for the left mouse button/mouse button 1. The script assumes that the binding has action set to touch.

Script properties

The script has the following script properties:

NOTE: If both drag_lock_x and drag_lock_y are set the game object will be locked to the nearest axis when the drag operation was started.

Input handling

You can let the cursor react to input in several ways:

Messages

The script will generate messages to game objects the cursor is interacting with and to the game object the cursor script is attached to for the following situations:

The messages sent to the game object where the cursor script is attached will have id and group as well as x and y (from action.x and action.y) passed in the message.

Drag objects

The cursor can drag game objects if the drag property is set. You can block drag operations on a single axis through drag_lock_x and drag_lock_y and you can set the drag threshold (ie how much the cursor needs to move before it is considered a drag event) using drag_threshold.

It is also possible to programmatically start a drag operation of a game object:

-- start dragging the game object with id '/go' vertically
msg.post("#cursor", cursor.START_DRAGGING, { id = hash("/go"), mode = cursor.DRAG_MODE_VERTICAL })

Blocking input events

You can listen for events generated by the cursor script and block execution of the events. This can be used to block drag, pressed and over events.

cursor.listen(cursor_script_url, cursor_event, callback_fn)

Set up a listener for a specific cursor event from a specific cursor script.

Example:

local cursor = require "in.cursor"

cursor.listen("#cursor", cursor.DRAG_START, function(message_id, message)
	-- prevent dragging of blue aliens
	if message.group == hash("blue") then
		return true -- return true to block the event
	end
end)

Resetting cursor state

It is recommended to reset the cursor state when the screen is minimized and/or has lost focus. This can be done by sending a message to the cursor script:

local cursor = require "in.cursor"

msg.post("#cursor", cursor.RESET)

-- or

cursor.reset("#cursor")