Skip to content

Tutorial 14. Input Manager

Timur Gafarov edited this page Sep 16, 2021 · 6 revisions

Dagon version: >=0.11

Dagon has a built-in input system that abstractizes the way how user interacts with the application. The simplest way is to listen to keyboard, mouse and joystick events in your scene (or in any EventListener implementation) and take action when particular event occurs. But this is suitable only for simple demos. In a real game you'll want to give players a possibility to customize game controls, so you are not going to hardcode any keys or joystick buttons in game code. Instead, you use abstract logic commands like "go forward", "jump", "fire", etc. Keyboard/joystick mappings for these commands should be defined in a user-editable configuration file. Dagon provides such a system, and it is available in EventManager class as inputManager property. Any EventListener has a shortcut to it, so you can use it directly from your scene.

A logic command in this system is called "binding". Bindings are defined in input.conf file in your game's directory. The following is a content of a simple input.conf that you can copy to your project:

forward: "kb_w, kb_up, gb_b";
back: "kb_s, kb_down, gb_a";
left: "kb_a, kb_left";
right: "kb_d, kb_right";
jump: "kb_space";
interact: "kb_e";

Binding definition format consists of device type and name(or number) coresponding to button or axis of this device.

kb - keyboard (kb_up, kb_w)
ma - mouse axis (ma_0)
mb - mouse button (mb_1)
ga - gamepad axis (ga_leftx, ga_lefttrigger)
gb - gamepad button (gb_a, gb_x)
va - virtual axis, has special syntax: va(kb_up, kb_down)

To use input manager, you don't need to subscribe to events, all is done with the getButton method:

override void onUpdate(Time t)
{
    if (inputManager.getButton("forward"))
        character.move(-camera.directionAbsolute, speed);
    if (inputManager.getButton("jump"))
        character.jump();
}

getButton is a continuous check, there are also getButtonDown and getButtonUp to check if a binding is triggered or released, respectively.

There's also getAxis method that returns a value in -1..1 range, which is useful for analog controls, such as steering in racing games. For example, you can assign joystick axes and several virtual axes to horizontal and vertical bindings in your configuration:

horizontal: "ga_leftx, va(kb_right, kb_left), va(gb_dpright, gb_dpleft)";
vertical: "ga_lefty, va(kb_down, kb_up), va(gb_dpdown, gb_dpup)";
override void onUpdate(Time t)
{
    spaceship.yaw(inputManager.getAxis("horizontal"));
    spaceship.pitch(inputManager.getAxis("vertical"));
}