runRandomMovement method

void runRandomMovement(
  1. double dt, {
  2. bool runOnlyVisibleInCamera = true,
  3. double speed = 20,
  4. int maxDistance = 50,
  5. int minDistance = 0,
  6. int timeKeepStopped = 2000,
})

Method that bo used in update method.

Implementation

void runRandomMovement(
  double dt, {
  bool runOnlyVisibleInCamera = true,
  double speed = 20,
  int maxDistance = 50,
  int minDistance = 0,
  int timeKeepStopped = 2000,

  /// milliseconds
}) {
  if (runOnlyVisibleInCamera &&
      !gameRef.camera.cameraRect.overlaps(position.rect)) return;
  if (_targetRandomMovement == Vector2.zero()) {
    if (checkInterval(_KEY_INTERVAL_KEEP_STOPPED, timeKeepStopped, dt)) {
      int randomX = Random().nextInt(maxDistance.toInt());
      randomX = randomX < minDistance ? minDistance : randomX;
      int randomY = Random().nextInt(maxDistance.toInt());
      randomY = randomY < minDistance ? minDistance : randomY;
      int randomNegativeX = Random().nextBool() ? -1 : 1;
      int randomNegativeY = Random().nextBool() ? -1 : 1;
      _targetRandomMovement = vectorPosition.translate(
        randomX.toDouble() * randomNegativeX,
        randomY.toDouble() * randomNegativeY,
      );
    }
  } else {
    bool canMoveX =
        (_targetRandomMovement.x - vectorPosition.x).abs() > speed;
    bool canMoveY =
        (_targetRandomMovement.y - vectorPosition.y).abs() > speed;

    bool canMoveLeft = false;
    bool canMoveRight = false;
    bool canMoveUp = false;
    bool canMoveDown = false;
    if (canMoveX) {
      if (_targetRandomMovement.x > vectorPosition.x) {
        canMoveRight = true;
      } else {
        canMoveLeft = true;
      }
    }
    if (canMoveY) {
      if (_targetRandomMovement.y > vectorPosition.y) {
        canMoveDown = true;
      } else {
        canMoveUp = true;
      }
    }

    if (canMoveLeft && canMoveUp) {
      moveUpLeft(speed, speed, onCollision: _cleanTargetMovementRandom);
    } else if (canMoveLeft && canMoveDown) {
      moveDownLeft(speed, speed, onCollision: _cleanTargetMovementRandom);
    } else if (canMoveRight && canMoveUp) {
      moveUpRight(speed, speed, onCollision: _cleanTargetMovementRandom);
    } else if (canMoveRight && canMoveDown) {
      moveDownRight(speed, speed, onCollision: _cleanTargetMovementRandom);
    } else if (canMoveRight) {
      moveRight(speed, onCollision: _cleanTargetMovementRandom);
    } else if (canMoveLeft) {
      moveLeft(speed, onCollision: _cleanTargetMovementRandom);
    } else if (canMoveUp) {
      moveUp(speed, onCollision: _cleanTargetMovementRandom);
    } else if (canMoveDown) {
      moveDown(speed, onCollision: _cleanTargetMovementRandom);
    } else {
      _cleanTargetMovementRandom();
    }
  }
}