Input
Pretty much everything input related is handled by the Input class.
Ref: InputEvent - InputEventMouse - InputEventMouseButton - InputEventMouseMotion
Mouse
Setting the mouse visibility is done via mouse_mode:
# Show mouse
Input.mouse_mode = Input.MOUSE_MODE_VISIBLE
# Hide mouse and capture
Input.mouse_mode = Input.MOUSE_MODE_CAPTURED
Mouse Position
Canvas items (which controls inherit from) can get the gobal mouse position aswell as the local mouse position.
GUI interaction
Mouseclicks on GUI controls register via Control._gui_input, which is a virtual method
func _gui_input(event):
if event is InputEventMouseButton:
if event.button_index == MOUSE_BUTTON_LEFT and event.pressed:
print("I've been clicked D:")
Propagates through a control node tree.
Drag and Drop interaction
Drag and Drop uses a seperate mechanic from the control class and inherited classes.
- Control._get_drag_data: to get data that can be dragged and dropped onto controls that expect drop data.
- Control._can_drop_data: to test if
datafrom a control's _get_drag_data() can be dropped. - Control._drop_data: to pass you the
datafrom a control's _get_drag_data() result. - Control.set_drag_preview: Shows the given control at the mouse pointer. A good time to call this method is in _get_drag_data().
Drag and Drop example using a texture (Video Tutorial):
extends TextureRect
func _get_drag_data(at_position):
var preview_texture = TextureRect.new() # Create a preview texture
preview_texture.texture = texture
preview_texture.expand_mode = 1
preview_texture.size = Vector2(30,30)
var preview = Control.new()
preview.add_child(preview_texture)
set_drag_preview(preview) # Shows the preview at the mouse pointer
texture = null
return preview_texture.texture
func _can_drop_data(_pos, data):
return data is Texture2D
func _drop_data(_pos, data):
texture = data
Info: The contol's own functionality can be overwritten with Control.set_drag_preview.
Keys
Keys trigger input events. These propagate up through the node tree calling until a node consumes it.
For gameplay input, _unhandled_input() and _unhandled_key_input() are usually a better fit as they allow the GUI to intercept the events first. How does it work?