moveTowardsTarget<T extends GameComponent> method

bool moveTowardsTarget<T extends GameComponent>({
  1. required T target,
  2. Function? close,
  3. double margin = 4,
  4. MovementAxis movementAxis = MovementAxis.all,
})

This method move this component to target Need use Movement mixin. Method that bo used in update method. return true if moved.

Implementation

bool moveTowardsTarget<T extends GameComponent>({
  required T target,
  Function? close,
  double margin = 4,
  MovementAxis movementAxis = MovementAxis.all,
}) {
  Rect rectPlayerCollision = target.rectCollision.inflate(margin);

  if (rectCollision.overlaps(rectPlayerCollision)) {
    close?.call();
    stopMove();
    return false;
  }

  double radAngle = getAngleFromTarget(target);
  Direction directionToMove = BonfireUtil.getDirectionFromAngle(
    radAngle,
  );
  final newDirectionToMove = _checkRestrictAxis(
    directionToMove,
    movementAxis,
  );
  if (newDirectionToMove != null) {
    directionToMove = newDirectionToMove;
  } else {
    stopMove();
    return false;
  }

  if (canMove(directionToMove, ignoreHitboxes: target.shapeHitboxes)) {
    if (directionToMove != lastDirection) {
      setZeroVelocity();
    }
    moveFromDirection(directionToMove);
    return true;
  } else {
    switch (directionToMove) {
      case Direction.right:
      case Direction.left:
      case Direction.up:
      case Direction.down:
        break;
      case Direction.upLeft:
        if (canMove(Direction.left)) {
          moveLeft();
          return true;
        } else if (canMove(Direction.up)) {
          moveUp();
          return true;
        }
        break;
      case Direction.upRight:
        if (canMove(Direction.right)) {
          moveRight();
          return true;
        } else if (canMove(Direction.up)) {
          moveUp();
          return true;
        }
        break;
      case Direction.downLeft:
        if (canMove(Direction.left)) {
          moveLeft();
          return true;
        } else if (canMove(Direction.down)) {
          moveDown();
          return true;
        }
        break;
      case Direction.downRight:
        if (canMove(Direction.right)) {
          moveRight();
          return true;
        } else if (canMove(Direction.down)) {
          moveDown();
          return true;
        }
        break;
    }
    stopMove();
    return false;
  }
}