flutterdarttrackingflamefortress

How to make Flutter flame components track each other?


We have a SpriteComponent (_fortress) which is a central object and another SpriteComponent (_player) which moves around _fortress. we want _fortress to track _player by rotating similar to a typical shooter game (see space fortress game for example).

    _fortress.add(
        RotateEffect.by(
          _fortress.position.angleTo(_player.position),
          LinearEffectController(1),
          onComplete: () => {},
        ),
      );

Solution

  • If you want to always be tracking the _player without any delay you can use the lookAt method in your update method:

    class Fortress extends SpriteComponent with HasGameRef<YourGameClass> {
      @override
      double nativeAngle = pi; // You only need to set this if your sprite isn't "looking straight up" in the image, if it is looking to the right it should be `pi` etc.
      
      @override
      void update(double dt) p
        super.update(dt);
        lookAt(gameRef.player.position);
      }
    }