Skip to content

Commit

Permalink
feat: Added transform to Rect (#1360)
Browse files Browse the repository at this point in the history
  • Loading branch information
wolfenrain committed Feb 21, 2022
1 parent bce2417 commit 1818be4
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
26 changes: 26 additions & 0 deletions packages/flame/lib/src/extensions/rect.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import 'dart:math' as math;
import 'dart:ui';

import '../../geometry.dart';
import 'matrix4.dart';
import 'offset.dart';
import 'size.dart';
import 'vector2.dart';
Expand Down Expand Up @@ -52,6 +53,31 @@ extension RectExtension on Rect {
];
}

/// Transform Rect using the transformation defined by [matrix].
///
/// **Note:** Rotation matrices will increase the size of the [Rect] but they
/// will not rotate it as [Rect] does not have any rotational values.
///
/// **Note:** Only non-negative scale transforms are allowed, if a negative
/// scale is applied it will return a zero-based [Rect].
///
/// **Note:** The transformation will always happen from the center of the
/// `Rect`.
Rect transform(Matrix4 matrix) {
// For performance reasons we are using the same logic from
// `Matrix4.transform2` but without the extra overhead of creating vectors.
return Rect.fromLTRB(
(topLeft.dx * matrix.m11) + (topLeft.dy * matrix.m21) + matrix.m41,
(topLeft.dx * matrix.m12) + (topLeft.dy * matrix.m22) + matrix.m42,
(bottomRight.dx * matrix.m11) +
(bottomRight.dy * matrix.m21) +
matrix.m41,
(bottomRight.dx * matrix.m12) +
(bottomRight.dy * matrix.m22) +
matrix.m42,
);
}

/// Creates bounds in from of a [Rect] from a list of [Vector2]
static Rect fromBounds(List<Vector2> pts) {
final minX = pts.map((e) => e.x).reduce(min);
Expand Down
10 changes: 10 additions & 0 deletions packages/flame/test/extensions/rect_test.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import 'dart:math' as math;

import 'package:flame/extensions.dart';
import 'package:flame_test/flame_test.dart';
import 'package:test/test.dart';

void main() {
Expand Down Expand Up @@ -36,5 +37,14 @@ void main() {
expect(r2.position.x, r1.left);
expect(r2.position.y, r1.top);
});

test('test transform', () {
final matrix4 = Matrix4.translation(Vector3(10, 10, 0));
const input = Rect.fromLTWH(0, 0, 10, 10);
final result = input.transform(matrix4);

expect(result.topLeft.toVector2(), closeToVector(10, 10));
expect(result.bottomRight.toVector2(), closeToVector(20, 20));
});
});
}

0 comments on commit 1818be4

Please sign in to comment.