positionsItselfAndKeepDistance<T extends GameComponent> method

bool positionsItselfAndKeepDistance<T extends GameComponent>(
  1. T target, {
  2. dynamic positioned(
    1. T
    )?,
  3. double radiusVision = 32,
  4. double? minDistanceFromPlayer,
  5. bool runOnlyVisibleInScreen = true,
})

Checks whether the component is within range. If so, position yourself and keep your distance. Method that bo used in update method.

Implementation

bool positionsItselfAndKeepDistance<T extends GameComponent>(
  T target, {
  Function(T)? positioned,
  double radiusVision = 32,
  double? minDistanceFromPlayer,
  bool runOnlyVisibleInScreen = true,
}) {
  if (runOnlyVisibleInScreen && !isVisible) return false;
  double distance = (minDistanceFromPlayer ?? radiusVision);

  Rect rectTarget = target.rectCollision;
  double centerXTarget = rectTarget.center.dx;
  double centerYTarget = rectTarget.center.dy;

  double translateX = 0;
  double translateY = 0;

  double speed = this.speed * dtUpdate;

  Rect rectToMove = rectCollision;

  translateX = rectToMove.center.dx > centerXTarget ? (-1 * speed) : speed;
  translateX = _adjustTranslate(
    translateX,
    rectToMove.center.dx,
    centerXTarget,
  );

  translateY = rectToMove.center.dy > centerYTarget ? (-1 * speed) : speed;
  translateY = _adjustTranslate(
    translateY,
    rectToMove.center.dy,
    centerYTarget,
  );

  double translateXPositive =
      (rectToMove.center.dx - rectTarget.center.dx).abs();

  double translateYPositive =
      (rectToMove.center.dy - rectTarget.center.dy).abs();

  if (translateXPositive >= distance &&
      translateXPositive > translateYPositive) {
    translateX = 0;
  } else if (translateXPositive > translateYPositive) {
    translateX = translateX * -1;
  }

  if (translateYPositive >= distance &&
      translateXPositive < translateYPositive) {
    translateY = 0;
  } else if (translateXPositive < translateYPositive) {
    translateY = translateY * -1;
  }

  if (translateX.abs() < dtSpeed && translateY.abs() < dtSpeed) {
    stopMove();
    positioned?.call(target);
    return false;
  } else {
    _moveComp(translateX, translateY);
    return true;
  }
}