Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add PositionComponent.toString #3095

Merged
merged 4 commits into from
Mar 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions packages/flame/lib/src/components/position_component.dart
Original file line number Diff line number Diff line change
Expand Up @@ -503,4 +503,16 @@ class PositionComponent extends Component
size.setValues(rect.width, rect.height);
topLeftPosition = rect.topLeft.toVector2();
}

@override
String toString() {
// ignore_for_file: no_runtimeType_toString
return '''
$runtimeType(
position: ${position.toStringWithMaxPrecision(4)},
size: ${size.toStringWithMaxPrecision(4)},
angle: $angle,
scale: $scale,
)''';
}
}
8 changes: 8 additions & 0 deletions packages/flame/lib/src/extensions/vector2.dart
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,14 @@ extension Vector2Extension on Vector2 {
/// Modulo/Remainder
Vector2 operator %(Vector2 mod) => Vector2(x % mod.x, y % mod.y);

/// Stringifies the Vector2 with a maximum precision of [maxPrecision].
String toStringWithMaxPrecision(int maxPrecision) {
final precision = pow(10, maxPrecision);
final truncatedX = (x * precision).truncate() / precision;
final truncatedY = (y * precision).truncate() / precision;
return 'Vector2($truncatedX, $truncatedY)';
}

/// Create a Vector2 with ints as input
static Vector2 fromInts(int x, int y) => Vector2(x.toDouble(), y.toDouble());

Expand Down
9 changes: 9 additions & 0 deletions packages/flame/test/extensions/vector2_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -488,6 +488,15 @@ void main() {
expectDouble(p2.length, math.sqrt(2));
expect(p2.x, p2.y);
});

test('toStringWithMaxPrecision', () {
final p1 = Vector2(1.123456789, 2.123456789);
expect(p1.toStringWithMaxPrecision(2), 'Vector2(1.12, 2.12)');
final p2 = Vector2(1, 2.123456789);
expect(p2.toStringWithMaxPrecision(3), 'Vector2(1.0, 2.123)');
final p3 = Vector2(-1, -2.123456789);
expect(p3.toStringWithMaxPrecision(3), 'Vector2(-1.0, -2.123)');
});
});

testRandom('Creating a Vector2 fromRadians points to the correct direction',
Expand Down
Loading