controls.gd 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. extends Control
  2. # Note for the reader:
  3. #
  4. # This demo conveniently uses the same names for actions and for the container nodes
  5. # that hold each remapping button. This allow to get back to the button based simply
  6. # on the name of the corresponding action, but it might not be so simple in your project.
  7. #
  8. # A better approach for large-scale input remapping might be to do the connections between
  9. # buttons and wait_for_input through the code, passing as arguments both the name of the
  10. # action and the node, e.g.:
  11. # button.connect("pressed", self, "wait_for_input", [ button, action ])
  12. # Member variables
  13. var player_actions = [ "move_up", "move_down", "move_left", "move_right", "jump" ]
  14. var action # To register the action the UI is currently handling
  15. var button # Button node corresponding to the above action
  16. func wait_for_input(action_bind):
  17. action = action_bind
  18. # See note at the beginning of the script
  19. button = get_node("bindings").get_node(action).get_node("Button")
  20. get_node("contextual_help").set_text("Press a key to assign to the '" + action + "' action.")
  21. set_process_input(true)
  22. func _input(event):
  23. # Handle the first pressed key
  24. if (event.type == InputEvent.KEY):
  25. # Register the event as handled and stop polling
  26. get_tree().set_input_as_handled()
  27. set_process_input(false)
  28. # Reinitialise the contextual help label
  29. get_node("contextual_help").set_text("Click a key binding to reassign it, or press the Cancel action.")
  30. if (not event.is_action("ui_cancel")):
  31. # Display the string corresponding to the pressed key
  32. button.set_text(OS.get_scancode_string(event.scancode))
  33. # Start by removing previously key binding(s)
  34. for old_event in InputMap.get_action_list(action):
  35. InputMap.action_erase_event(action, old_event)
  36. # Add the new key binding
  37. InputMap.action_add_event(action, event)
  38. func _ready():
  39. # Initialise each button with the default key binding from InputMap
  40. var input_event
  41. for action in player_actions:
  42. # We assume that the key binding that we want is the first one (0), if there are several
  43. input_event = InputMap.get_action_list(action)[0]
  44. # See note at the beginning of the script
  45. var button = get_node("bindings").get_node(action).get_node("Button")
  46. button.set_text(OS.get_scancode_string(input_event.scancode))
  47. button.connect("pressed", self, "wait_for_input", [action])