angleTo method
Returns the angle formed by component's orientation vector and a vector
starting at component's absolute position and ending at target
. I.e.
how much the current component need to rotate to face the target. This
angle is measured in clockwise direction. target
should be in
absolute/world coordinate system.
Uses nativeAngle
to decide the orientation direction of the component.
See lookAt
to make the component instantly rotate towards target.
Note: If target coincides with the current component's position, then it is treated as being north.
Implementation
double angleTo(Vector2 target) {
final direction = target - absolutePosition;
if (direction.isZero()) {
// If the target coincides with the component's position, we treat it as
// being north.
return -nativeAngle % tau;
}
final parentAbsoluteScale = _parentAbsoluteScale;
final targetAngle = math.atan2(
direction.x * scale.x.sign,
-direction.y * scale.y.sign,
);
final angleDifference = targetAngle - absoluteAngle - nativeAngle;
final hasOddFlips = parentAbsoluteScale.x.isNegative ^
parentAbsoluteScale.y.isNegative ^
scale.x.isNegative ^
scale.y.isNegative;
final hasSelfYFlip =
!parentAbsoluteScale.y.isNegative && scale.y.isNegative;
final result = (hasOddFlips ? -1 : 1) * angleDifference +
(hasSelfYFlip ? 1 : 0) * math.pi;
return result.toNormalizedAngle();
}