followComponent method
bool
followComponent(
- GameComponent target,
- double dt, {
- required dynamic closeComponent(),
- double margin = 10,
This method move this component to target Need use Movement mixin. Method that bo used in update method. return true if moved.
Implementation
bool followComponent(
GameComponent target,
double dt, {
required Function(GameComponent) closeComponent,
double margin = 10,
}) {
final comp = target.rectConsideringCollision;
double centerXPlayer = comp.center.dx;
double centerYPlayer = comp.center.dy;
double translateX = 0;
double translateY = 0;
double speed = this.speed * dt;
Rect rectToMove = rectConsideringCollision;
translateX = rectToMove.center.dx > centerXPlayer ? (-1 * speed) : speed;
translateX = _adjustTranslate(
translateX,
rectToMove.center.dx,
centerXPlayer,
);
translateY = rectToMove.center.dy > centerYPlayer ? (-1 * speed) : speed;
translateY = _adjustTranslate(
translateY,
rectToMove.center.dy,
centerYPlayer,
);
Rect rectPlayerCollision = Rect.fromLTWH(
comp.left - margin,
comp.top - margin,
comp.width + (margin * 2),
comp.height + (margin * 2),
);
if (rectToMove.overlaps(rectPlayerCollision)) {
closeComponent(target);
if (!isIdle) {
idle();
}
return false;
}
translateX /= dt;
translateY /= dt;
bool moved = false;
if (translateX > 0 && translateY > 0) {
moved = moveDownRight(translateX, translateY);
} else if (translateX < 0 && translateY < 0) {
moved = moveUpLeft(translateX.abs(), translateY.abs());
} else if (translateX > 0 && translateY < 0) {
moved = moveUpRight(translateX, translateY.abs());
} else if (translateX < 0 && translateY > 0) {
moved = moveDownLeft(translateX.abs(), translateY);
} else {
if (translateX > 0) {
moved = moveRight(translateX);
} else if (translateX < 0) {
moved = moveLeft(translateX.abs());
}
if (translateY > 0) {
moved = moveDown(translateY);
} else if (translateY < 0) {
moved = moveUp(translateY.abs());
}
}
if (!moved) {
idle();
return false;
}
return true;
}