In this video, we add the ability to skip the obstacle course’s overview animation.
We already saw the Input
object, which we used to
calculate the player’s movement direction. We can also use it to know if
the player is pressing or releasing a key in a given frame.
We call that polling. Typically, every frame, we check for the state of some input actions and react accordingly.
Godot has another powerful mechanism to process and consume input events as they occur.
You can define the _unhandled_input()
function to
receive each event individually.
This function receives every input in the form of an
event
argument:
Godot calls it once per node and input event.
You can test if an action is pressed by calling the
is_action_pressed()
function on the input
event
. This is similar to calling
Input.is_action_just_pressed()
.
func _unhandled_input(event: InputEvent) -> void:
if event.is_action_pressed("start_game"):
start_game()
Unlike the Input
object, the dedicated input functions
can consume input events, preventing other nodes in the game from
receiving them.
Imagine that you’re making a hack-and-slash game where the player moves by clicking.
When they open their inventory, the player also clicks to select and move items. You don’t want clicking in the inventory to cause the player to move.
You can consume clicks in the inventory using the input functions, preventing the player’s character from receiving them.
You do it by first calling get_tree()
to get the
SceneTree
object and calling its
set_input_as_handled()
function.
func _unhandled_input(event: InputEvent) -> void:
if event.is_action_pressed("click"):
# Consume the input event, preventing other nodes from receiving it.
get_tree().set_input_as_handled()
Another benefit is that you can turn these input functions on and off
without turning off the _process()
function, as we saw in
the code.
# Turn off calls to the _unhandled_input() function on this node.
set_process_unhandled_input(false)
There is more depth to input handling in Godot, and these two systems have more reasons to coexist. But you’ll need some more experience creating games for all the extra features to make sense.