Challenge: Change animations of a Sprite with Tap Flutter with Flame 21

- Andrés Cruz

En español

Challenge: Change animations of a Sprite with Tap Flutter with Flame 21

As a small challenge, you must implement the following logic in the animated sprite sheet component, and you must implement a very simple logic to vary the animation each time you tap on the screen; to do this, you can use a numerical property which will indicate the animation to be executed:

  • animationIndex with the value of zero, the death animation is displayed.
  • animationIndex with the value of one, the idle animation is displayed.
  • animationIndex with the value of two, the jump animation is displayed.
  • animationIndex with the value of three, the walking animation is displayed.
  • animationIndex with the value of four, the running animation is displayed.

Challenge resolution

As a resolution, we can use a switch in which we change the animation according to the animationIndex value that we will increase each time the "tap" occurs on the screen:

lib\components\player_sprite_sheet_component.dart

*** 
  int animationIndex = 0;
*** 
  @override
  bool onTapDown(TapDownInfo info) {
    super.onTapDown(info);
    print(info);

    animationIndex++;

    if (animationIndex > 4) animationIndex = 0;

    switch (animationIndex) {
      case 1:
        animation = dinoIdleAnimation;
        break;
      case 2:
        animation = dinoJumpAnimation;
        break;
      case 3:
        animation = dinoWalkAnimation;
        break;
      case 4:
        animation = dinoRunAnimation;
        break;
      case 0:
      default:
        animation = dinoDeadAnimation;
        break;
    }

    return true;
  }

As you can see, we can easily vary from one animation to another using a numerical value that corresponds to an index of the animation that we want to animate.

This snippet is part of the complete project:

https://github.com/libredesarrollo/flame-curso-libro-dinojump03

In which, we see how to create the animation step by step; the important thing is to note how simple it is to make this type of integration, each key on the keyboard is associated with a different action such as walking, jumping or running, which in turn is associated with a different animation that is easily changed by assigning a value to the animation property a different value.

Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.