Input Action Mapping

One interesting way to generalize input in games is known as action mapping. Basically instead of keys (or buttons) being pressed or released, objects react to when actions are “pressed” and “released”. The largest benefit of using this method when programming input for games is when your project requires input from multiple devices (or support for multiple devices in the future).

Actions are generated from device handlers and propagated to game objects for evaluation. Device handlers handle input device events (such as key press/release) and create the corresponding action.

This worked especially well when developing Project Warpy for the XBOX/PC as debugging on the PC requires keyboard input, while the XBOX only accepts controller input.

Here’s a quick snippet on how you can implement this into your own games:

enum Action
{
    MOVE_LEFT,
    MOVE_RIGHT,
    JUMP
};

class KeyboardHandler
{
public:
    void onPress(char key)
    {
        if (key == LEFT_ARROW)
            gameWorld.propagateKeyPress(MOVE_LEFT);
        if (key == RIGHT_ARROW)
            gameWorld.propagateKeyPress(MOVE_RIGHT);
    }

    void onRelease(char key)
    {
        if (key == LEFT_ARROW)
            gameWorld.propagateKeyRelease(MOVE_LEFT);
        if (key == RIGHT_ARROW)
            gameWorld.propagateKeyRelease(MOVE_RIGHT);
    }
};

Of course, this is not very useful if you only need support for 1 type of input device. But… say I wanted support for the XBOX 360 controller.

class ControllerHandler
{
public:
    void onPress(Button button)
    {
        if (button == DPAD_LEFT)
            gameWorld.propagateKeyPress(MOVE_LEFT);
        if (button == DPAD_RIGHT)
            gameWorld.propagateKeyPress(MOVE_RIGHT);
    }

    void onRelease(Button button)
    {
        if (button == DPAD_LEFT)
            gameWorld.propagateKeyRelease(MOVE_LEFT);
        if (button == DPAD_RIGHT)
            gameWorld.propagateKeyRelease(MOVE_RIGHT);
    }
};

This works for any device (or device library for that matter) as long as propagateKeyPress and propagateKeyRelease are called in the right place and because the game objects react to the Action enum, no extra coding on the game object side is required.

1 Response to “Input Action Mapping”


Leave a Reply