Skip to content

Commit

Permalink
feat: Add PositionComponent.toString (#3095)
Browse files Browse the repository at this point in the history
Adds a `toString` override for `PositionComponent` so that one can see
all its properties easily.
  • Loading branch information
spydon committed Mar 25, 2024
1 parent 6daf7a3 commit b1f0198
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
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

0 comments on commit b1f0198

Please sign in to comment.