Skip to content
Download

Keyboard and gamepad with actions

You want the game to work with the keyboard and with a gamepad, and changing a key shouldn’t mean touching the code.

An action is a name, such as pular (jump), tied to one or more keys and buttons. In the code, you ask about the action:

void Player::onUpdate() {
hspeed = axis("esquerda", "direita") * 2.0f;
if (pressed("pular")) vspeed = -4.0f;
}
  • held("pular") is true while the action is held.
  • pressed("pular") is true only on the step it was pressed: once per tap.
  • released("pular") is true only on the step it was let go.
  • axis("esquerda", "direita") returns a number from -1 to 1: -1 with the first action, 1 with the second, 0 with neither or both. On the gamepad’s analog stick, it returns values in between.

Open Projeto › Configurações do projeto… (Project › Project settings) and go to Ações de entrada (input actions). There you create actions, change their names and choose the keys and buttons of each one. See Project settings.

A new project (the Vazio template, empty) already comes with six actions:

Action Keyboard Gamepad
esquerda (left) ←, A D-pad ←, stick ←
direita (right) →, D D-pad →, stick →
cima (up) ↑, W D-pad ↑, stick ↑
baixo (down) ↓, S D-pad ↓, stick ↓
pular (jump) Space A
acao (action) X, Enter X

The Primeiro jogo template (first game) brings the four directions plus atirar (shoot), confirmar (confirm) and sair (quit).

  • The first connected gamepad is used. You can plug it in and out while the game is running.
  • The buttons are Pad:A, Pad:B, Pad:X, Pad:Y, Pad:Start, Pad:Back, Pad:LB and Pad:RB, and the D-pad is Pad:Up, Pad:Down, Pad:Left and Pad:Right.
  • The left stick is Pad:LeftX-, Pad:LeftX+, Pad:LeftY- and Pad:LeftY+. It has a dead zone of 0.25: light touches don’t count.

An action that doesn’t exist shows up once as an error in the Saída (Output). Check that the name in the code is the same as in the project settings, letter by letter.

The functions that take a key, such as held(Key::Space), still work. Use them for quick tests; for the game, prefer actions.