Challenge: Move sprite by pressing directional arrows in Flutter Flame

- Andrés Cruz

En español
Challenge: Move sprite by pressing directional arrows in Flutter Flame

We already know how to use the keyboard events in Flame at the class and component level, now, as a challenge, adapt the previous code and, in addition to the arrows, you can use the w (up), d (right), s keys (below) and a (left).

Resolution challenge

To add the typical WASD keys in our script, we can do a simple conditional with an OR:

@override
bool onKeyEvent(
    RawKeyEvent event,
    Set<LogicalKeyboardKey> keysPressed,
  ) {
    if (keysPressed.contains(LogicalKeyboardKey.arrowUp) ||
        keysPressed.contains(LogicalKeyboardKey.keyW)) {
      position = Vector2(centerX, centerY--);
    } else if (keysPressed.contains(LogicalKeyboardKey.arrowDown) ||
        keysPressed.contains(LogicalKeyboardKey.keyS)) {
      position = Vector2(centerX, centerY++);
    } else if (keysPressed.contains(LogicalKeyboardKey.arrowRight) ||
        keysPressed.contains(LogicalKeyboardKey.keyD)) {
      position = Vector2(centerX++, centerY);
    } else if (keysPressed.contains(LogicalKeyboardKey.arrowLeft) ||
        keysPressed.contains(LogicalKeyboardKey.keyA)) {
      position = Vector2(centerX--, centerY);
    }
    return true;
}

As you can see, the logic is simple, it is enough to detect the typical WASD and direction keys and move the player in the appropriate position; remember that for:

  • If X is positive, it moves to the right and negative to the left.
  • And if it is positive downwards and negative upwards.
Andrés Cruz

Desarrollo con Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz en Udemy

Acepto recibir anuncios de interes sobre este Blog.