Unhandled Input
Part of the Input and Movement section of Coddy's Godot journey. Lesson 6 of 28.
Godot can also tell you about keys. Each key press and each key release is an event. Godot sends every event to a function called _unhandled_input:
func _unhandled_input(event):
if event.is_action_pressed("action"):
print("Action!")The function runs once per event, not every frame. event.is_action_pressed("action") is true when the event is the action key going down. For the release, it is false.
not turns true into false and back. This line switches a node on and off:
$Lamp.visible = not $Lamp.visibleThe hero has a hidden Lamp on its antenna. The action keys are E and Enter.
Challenge
EasySwitch the hero's lamp on and off with a key.
- In
_unhandled_input(event), add anifforevent.is_action_pressed("action"). - Inside it, set
$Lamp.visibleto the opposite of what it is.
Press Play and press E: the lamp turns on, and the next press turns it off. Then Check.
Try it yourself
extends Node2D
func _unhandled_input(event):
pass
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Input and Movement
5Project: Platformer Hero
Hero: RunHero: JumpPractice on your own: Godot playground