controls.gd 2.2 KB

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