ActionRemapButton.gd 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. extends Button
  2. @export var action := "ui_up"
  3. func _ready() -> void:
  4. assert(InputMap.has_action(action))
  5. set_process_unhandled_key_input(false)
  6. display_current_key()
  7. func _toggled(is_button_pressed: bool) -> void:
  8. set_process_unhandled_key_input(is_button_pressed)
  9. if is_button_pressed:
  10. text = "<press a key>"
  11. modulate = Color.YELLOW
  12. release_focus()
  13. else:
  14. display_current_key()
  15. modulate = Color.WHITE
  16. # Grab focus after assigning a key, so that you can go to the next
  17. # key using the keyboard.
  18. grab_focus()
  19. # NOTE: You can use the `_input()` callback instead, especially if
  20. # you want to work with gamepads.
  21. func _unhandled_key_input(event: InputEvent) -> void:
  22. # Skip if pressing Enter, so that the input mapping GUI can be navigated
  23. # with the keyboard. The downside of this approach is that the Enter
  24. # key can't be bound to actions.
  25. if event is InputEventKey and event.keycode != KEY_ENTER:
  26. remap_action_to(event)
  27. button_pressed = false
  28. func remap_action_to(event: InputEvent) -> void:
  29. # We first change the event in this game instance.
  30. InputMap.action_erase_events(action)
  31. InputMap.action_add_event(action, event)
  32. # And then save it to the keymaps file.
  33. KeyPersistence.keymaps[action] = event
  34. KeyPersistence.save_keymap()
  35. text = event.as_text()
  36. func display_current_key() -> void:
  37. var current_key := InputMap.action_get_events(action)[0].as_text()
  38. text = current_key