Godot’s Control nodes provide a comprehensive system for handling user input. Input events are automatically propagated through the scene tree, allowing UI elements to respond to mouse clicks, touch events, keyboard input, and more.
Input events are filtered by z-order, focus state, and the mouse_filter property before reaching a control.
Override _gui_input() to handle input events on UI elements:
extends Controlfunc _gui_input(event: InputEvent): if event is InputEventMouseButton: if event.button_index == MOUSE_BUTTON_LEFT and event.pressed: print("Left mouse button clicked!") accept_event() # Prevent event from propagating
public override void _GuiInput(InputEvent @event){ if (@event is InputEventMouseButton mb) { if (mb.ButtonIndex == MouseButton.Left && mb.Pressed) { GD.Print("Left mouse button clicked!"); AcceptEvent(); // Prevent event from propagating } }}
Call accept_event() to mark an input as handled and prevent it from propagating to nodes below.
Only one Control can have focus at a time. The focused control receives keyboard input:
var line_edit = LineEdit.new()add_child(line_edit)# Grab focus programmaticallyline_edit.grab_focus()# Check if control has focusif line_edit.has_focus(): print("LineEdit is focused")
var lineEdit = new LineEdit();AddChild(lineEdit);// Grab focus programmaticallylineEdit.GrabFocus();// Check if control has focusif (lineEdit.HasFocus()){ GD.Print("LineEdit is focused");}
func _gui_input(event: InputEvent): if event is InputEventMouseButton: var mb = event as InputEventMouseButton if mb.button_index == MOUSE_BUTTON_LEFT: if mb.pressed: print("Mouse pressed at: ", mb.position) else: print("Mouse released at: ", mb.position) elif event is InputEventMouseMotion: var mm = event as InputEventMouseMotion print("Mouse moved to: ", mm.position) print("Mouse relative motion: ", mm.relative)
func _gui_input(event: InputEvent): if event is InputEventKey: var key = event as InputEventKey if key.pressed and key.keycode == KEY_ENTER: print("Enter key pressed!") accept_event()
public override void _GuiInput(InputEvent @event){ if (@event is InputEventKey key) { if (key.Pressed && key.Keycode == Key.Enter) { GD.Print("Enter key pressed!"); AcceptEvent(); } }}
func _gui_input(event: InputEvent): if event is InputEventScreenTouch: var touch = event as InputEventScreenTouch if touch.pressed: print("Touch started at: ", touch.position) else: print("Touch ended") elif event is InputEventScreenDrag: var drag = event as InputEventScreenDrag print("Dragging with velocity: ", drag.velocity)