Custom key binding, am I on the right track?

Wondering if I am on the right track for future proofing input controls so that a user can set custom keys or use a gamepad.

Right now I have two enums:

enum Input

enum InputType

Then in my main game1.cs update loop I have a call to my function control()

void Control()
    cState = pState; // current/previous keyboard state
    cState = Keyboard.GetState();

    Input input;
        InputType type;

        if (cState.IsKeyDown(Keys.W)) // Plan is to change Keys.W somehow later
        input = Input.Up;
        type = InputType.Hold;

    /* Similar functions with pState and cState to determine hold, press or release. */

ScreenManager.Control(input, type); // Passes it through to screen manager and current screen updates/controls


So later in my screens I can just make a check for Input.Up && InputType.Press to just for example move a menu item up once.

Does this seem like a good way to go, say I want to change up from W key to Up key or anything else, I only change once in my code?

Could I easily adapt this to a user in a settings menu inputting their own key?

That is a good way doing it. Separating the physical input method from the input action will work well to allow the user to customise controls.

I’ve done something like this before, mapping an object (like your input enum, but I used object to make it usable in general) to a set of keys and a set of gamepad buttons. I’m sure I have the code somewhere, but it was based onthis. That might be useful to you :slight_smile:

Thanks this is quite useful, I may refactor a little.

How would I then go about letting a user set say Keys.W or GamePad.Up to Action(Up)?

Check out the action mapping region of the sample. The mapping is hardcoded here, but you could create functions to add and remove actions from the map. You could hardcode the possible actions as an enum and have that be the type of an action in your Input class, or use object instead so you can choose what to use and don’t have to change anything in the class when including it in a game. Might be nicest to change the type for each game so you get IntelliSense. Then use IsActionPressed to check if a button registered for an action is pressed.

Here’s a gist with the implementation I did of this.

I would have a list of Keys and assigned Actions, and a list of GamePadButtons and assigned Actions. There is nothing to stop you from having the same Action assigned to multiple keys and gamepad buttons.

And then allowing the user to remap?

something like (forgive my syntax):

actionKey = Keyboard.getstate().getkeys()

stuck in loop whilst waiting on a menu item displaying something like “press button for action”

I think that would work, yeah.