From b1f01986b440ac18bb35b0d76963b2c66f49ea33 Mon Sep 17 00:00:00 2001 From: Lukas Klingsbo Date: Mon, 25 Mar 2024 11:39:03 +0100 Subject: [PATCH] feat: Add PositionComponent.toString (#3095) Adds a `toString` override for `PositionComponent` so that one can see all its properties easily. --- .../flame/lib/src/components/position_component.dart | 12 ++++++++++++ packages/flame/lib/src/extensions/vector2.dart | 8 ++++++++ packages/flame/test/extensions/vector2_test.dart | 9 +++++++++ 3 files changed, 29 insertions(+) diff --git a/packages/flame/lib/src/components/position_component.dart b/packages/flame/lib/src/components/position_component.dart index 8a8498b53dd..39d49e97cde 100644 --- a/packages/flame/lib/src/components/position_component.dart +++ b/packages/flame/lib/src/components/position_component.dart @@ -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, +)'''; + } } diff --git a/packages/flame/lib/src/extensions/vector2.dart b/packages/flame/lib/src/extensions/vector2.dart index a7265e18c90..5fbec23e2f2 100644 --- a/packages/flame/lib/src/extensions/vector2.dart +++ b/packages/flame/lib/src/extensions/vector2.dart @@ -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()); diff --git a/packages/flame/test/extensions/vector2_test.dart b/packages/flame/test/extensions/vector2_test.dart index 5cba3ea1bce..69f337744c2 100644 --- a/packages/flame/test/extensions/vector2_test.dart +++ b/packages/flame/test/extensions/vector2_test.dart @@ -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',