Finite State Machine demo state machine sending input twice to the state, why?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Alexander Dahl

Hi!

I’ve tried out Godot and I really like it. I want to implement a state machine but I’m having trouble understanding why the input is sent twice to the state node while the state machine is only recording the input once. The question is for this demo: https://github.com/godotengine/godot-demo-projects/tree/master/2d/finite_state_machine

So the demo has a player_state_machine.gd that has a number of states, one state being idle.gd

The player_state_machine.gd has an input function that it inherits from a state machine class. It has a function that looks like this:

func _input(event):
    print("send input to the state " + current_state.name) # I added this print
    current_state.handle_input(event)

and the Idle.gd has the following code:

func handle_input(event):
    print("received input from state machine") # I added this print
    return .handle_input(event)

When running the project with the added prints the console shows that the idle.gd input is received twice when the state switches to the Idle state.

example output from the console:

send input to the state Idle
received input from state machine
received input from state machine
send input to the state Move
send input to the state Idle
received input from state machine
received input from state machine

The expected behavior for me is that the each sent input event should correspond to one received input event, which is why I’m struggling to understand.

I would love if someone can help me understand! This is also my first question here, any feedback on how I should phrase the question better is appreciated.

:bust_in_silhouette: Reply From: Alexander Dahl

I used the debug tool in Godot to look at the stack trace. Turns out since the input event is triggered on all _input functions (as is intended and documented in Godot) the function is triggered both on the base state machine class (https://github.com/godotengine/godot-demo-projects/blob/master/2d/finite_state_machine/state_machine/state_machine.gd)

as well as the player state machine class (https://github.com/godotengine/godot-demo-projects/blob/master/2d/finite_state_machine/player/player_state_machine.gd)

That resulted in it being called twice. I don’t know the design choices of the author of the demo, but I think the inputs should only be handled by the player state machine and not by the base class. Simply removing the _input function from the base class fixed the issue.