In my game, there is a rocket launch animation.
The rocket is at the top of the screen, and the target is at the bottom of the screen. When I select a launch target to launch, there will be an angle rotation error.
The smaller the angle required to rotate to the target, the smaller the error. Conversely, the larger the angle, the larger the error.
enter image description here
static void move(Forge2DGame<Forge2DWorld> game, Vector2 targetPosition,
ParamVoidCallback callback) {
rocket?.removeFromParent();
Vector2 startPosition = MyGame.getBallPosition(game);
RocketAnimation newRocket = RocketAnimation();
targetPosition.y -= newRocket.size.y / 2;
final effectEffect = MoveEffect.to(
targetPosition,
EffectController(duration: 1),
);
double angle = calculateMinimumAngleDifference(
startPosition.x, startPosition.y, targetPosition.x, targetPosition.y);
debugPrint("angle:$angle");
final rotateEffect = RotateEffect.to(
angle,
EffectController(duration: 3),
);
newRocket.add(effectEffect);
newRocket.add(rotateEffect);
game.world.add(newRocket);
}
static double calculateMinimumAngleDifference(
double startX, double startY, double targetX, double targetY) {
double angle1 = atan2(startY, startX);
double angle2 = atan2(targetY, targetX);
double diff = (angle2 + pi - angle1);
debugPrint("angle1:$angle1");
debugPrint("angle2:$angle2");
if (diff > pi) {
diff -= 2 * pi;
} else if (diff < -pi) {
diff += 2 * pi;
}
debugPrint("angle3:$diff");
return diff;
}
Hope to get a correct rotation angle