seeAndMoveToAttackRange method

void seeAndMoveToAttackRange({
  1. required dynamic positioned(
    1. Player
    ),
  2. BoolCallback? notObserved,
  3. double radiusVision = 32,
  4. double? minDistanceCellsFromPlayer,
  5. bool runOnlyVisibleInScreen = true,
})

Checks whether the player is within range. If so, move to it.

Implementation

void seeAndMoveToAttackRange({
  required Function(Player) positioned,
  // return true to stop move.
  BoolCallback? notObserved,
  double radiusVision = 32,
  double? minDistanceCellsFromPlayer,
  bool runOnlyVisibleInScreen = true,
}) {
  if (isDead) return;
  if (runOnlyVisibleInScreen && !isVisible) return;

  seePlayer(
    radiusVision: radiusVision,
    observed: (player) {
      positioned(player);

      Rect playerRect = player.rectCollision;
      double distance = (minDistanceCellsFromPlayer ?? radiusVision);

      Vector2 myPosition = Vector2(
        center.x,
        center.y,
      );

      Vector2 playerPosition = Vector2(
        playerRect.center.dx,
        playerRect.center.dy,
      );

      double dist = myPosition.distanceTo(playerPosition);

      if (dist >= distance) {
        stopMove();
        return;
      }

      moveFromAngle(
        getInverseAngleFromPlayer(),
      );
    },
    notObserved: () {
      bool stop = notObserved?.call() ?? true;
      if (stop) {
        stopMove();
      }
    },
  );
}