Animation is not triggered when player shooting bullets

44 Views Asked by At

I'm making a 2d pixel game with flutter flame and trying to add player shooting method. When player presses Q key, Bullet class is created and performs the way that I want it to be shooted. However, the player's sprite animation is not played when shooting bullets.

This is the update method that consequtively updates player's states, including movements. So, if Q button is pressed, hasShooted turns true and triggers _shootBullet() method.


  @override
  void update(double dt) {
      if (hasShooted) {
        _shootBullet();
      }
    }
    super.update(dt);
  }

This is onKey event that detects if player pressed Q button to shoot bullets.

  @override
  bool onKeyEvent(RawKeyEvent event, Set<LogicalKeyboardKey> keysPressed) {
    //Checks if the player shoots bullet.
    hasShooted = keysPressed.contains(LogicalKeyboardKey.keyQ) && !event.repeat;

    return super.onKeyEvent(event, keysPressed);
  }

Lastly, this is _shootBullet().

  void _shootBullet() {
    current = PlayerState.attack; //this triggers the sprite animation.

    Bullet bullet = Bullet(
      moveVertically: false,
      position: (bulletHorizontalDirection == 1)
          ? Vector2(position.x + 20, position.y + 16)
          : Vector2(position.x - 20, position.y + 16),
      moveDirection: bulletHorizontalDirection,
      hitbox: RectangleHitbox(
        collisionType: CollisionType.passive,
        position: Vector2(2, 9),
        size: Vector2(22, 10),
      ),
    );
    parent?.add(bullet);

    hasShooted = false;
  }

I tried making shooting method a async function, so that the bullet can be created after the animation has been played, but this not only stopped creating bullet but also didn't play the animation.

  void _shootBullet() async {
    current = PlayerState.attack;
    await animationTicker?.completed;

     //creates Bullet...
   }

0

There are 0 best solutions below