Godot Input Mapping
In almost every project, I’ve always wondered about the “perfect” way to handle user input and keybinds. Godot provides pretty nice input mapping through project settings, and they are also configurable during runtime.
This approach uses those binds, and tracks keys that are held down.
var binds:Dictionary
func _ready():
update_inputmap()
func update_inputmap():
for i in InputMap.get_actions():
binds[i] = false
func _unhandled_input(event: InputEvent) -> void:
for b in binds.keys():
if event.is_action_pressed(b):
binds[b] = true
if event.is_action_released(b):
binds[b] = false
func _process(delta: float) -> void:
if binds["move_right"]:
player.move(Vector2.RIGHT)
if binds["move_left"]:
player.move(Vector2.LEFT)
if binds["jump"]:
binds["jump"] = false # Reset until next key press.
player.jump()
If the binds are updated at runtime, update_inputmap()
should be called again.
This is probably not “one size fits all”, but it has served me well and in my very humble opinion looks clean.