How do I swap back and forth from controller to keyboard inputs?

Godot Version

4.6.2

Question

In my game I want you to be able to use a controller or a keyboard. How do I use scripts to swap the controls.

You need to map the inputs for your projects so you can use keys, mouse or other controller (Project→Project Settings→ InputMap).

Yes, I have that but is there a way I can choose to use keyboard then swap to controller in-game?

The thing is you will map for both. So, you will as an example, move_forward and add KEY_W and Axis 0 1 or so. You map to support both and use anything you want. The mapping stays. If you want to, you can remove mapping and create a new one by code but I don’t think you need to do that.
This is an example:

func add_action_key(action, key_code):

if InputMap.has_action(action):
	InputMap.erase_action(action)

InputMap.add_action(action)
var event
event = InputEventKey.new()
event.keycode = key_code
InputMap.action_add_event(action, event)

#print_debug(InputMap.get_actions())

#-----------------------------------------------------

Setup used inputs

func setup_input():

Input.mouse_mode = Input.MOUSE_MODE_CAPTURED

add_action_key("move_left", KEY_A)
add_action_key("move_right", KEY_D)
add_action_key("move_forward", KEY_W)
add_action_key("move_backward", KEY_S)

add_action_key("move_jump", KEY_SPACE)

add_action_key("move_crouch_stand", KEY_C)

add_action_key("move_run", KEY_SHIFT)

add_action_key("action_interact", KEY_E)
1 Like

They’re both always active.

If you want to show on-screen buttons based on what the user is currently using, check out my Controller Plugin. You can either borrow code from it, or just use it. It tracks the last input used, and has a function called Controller.get_action_icon(), that when called with the name of a mapped action, looks to see what the last input type the player used was, and returns a Texture2D you can display to the user. It works with mouse, keyboard, and Xbox, PS, and Nintendo gamepads out of the box, and you can use your own images if you don’t like the free Kenney ones.

2 Likes

Thank you both!!!

2 Likes