Skip to content

Commit

Permalink
feat: Add helper methods to create matrix4 with sensible defaults
Browse files Browse the repository at this point in the history
  • Loading branch information
luanpotter committed Feb 10, 2025
1 parent 1dbb443 commit 09c28ca
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
35 changes: 35 additions & 0 deletions packages/flame_3d/lib/src/game/transform_3d.dart
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,41 @@ class Transform3D extends ChangeNotifier {
return Transform3D()..setFromMatrix4(matrix);
}

/// Creates a [Transform3D] from the given broken down
/// parameters and sensible defaults:
/// - [position] defaults to no translation;
/// - [rotation] defaults to no rotation;
/// - [scale] defaults to no scaling.
factory Transform3D.compose({
Vector3? position,
Quaternion? rotation,
Vector3? scale,
}) {
final matrix = matrix4(
position: position,
rotation: rotation,
scale: scale,
);
return Transform3D.fromMatrix4(matrix);
}

/// Creates a transform-3d-type [Matrix4] from the given broken down
/// parameters and sensible defaults:
/// - [position] defaults to no translation;
/// - [rotation] defaults to no rotation;
/// - [scale] defaults to no scaling.
static Matrix4 matrix4({
Vector3? position,
Quaternion? rotation,
Vector3? scale,
}) {
return Matrix4.compose(
position ?? Vector3.zero(),
rotation ?? Quaternion.identity(),
scale ?? Vector3.all(1),
);
}

/// Clone of this.
Transform3D clone() => Transform3D.copy(this);

Expand Down
34 changes: 34 additions & 0 deletions packages/flame_3d/test/transform_3d_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -46,5 +46,39 @@ void main() {
closeToMatrix4(matrix2, epsilon),
);
});

test('can create matrix4 using some parameters with sensible defaults', () {
final matrix1 = Transform3D.matrix4(
position: Vector3(1, 2, 3),
);
final transform1 = Transform3D.fromMatrix4(matrix1);
expect(transform1.position, closeToVector3(Vector3(1, 2, 3), epsilon));
expect(
transform1.rotation,
closeToQuaternion(Quaternion.identity(), epsilon),
);
expect(transform1.scale, closeToVector3(Vector3.all(1), epsilon));

final transform2 = Transform3D.compose(
rotation: Quaternion(0.1, 0.2, 0.3, 0.4).normalized(),
);
expect(transform2.position, closeToVector3(Vector3.zero(), epsilon));
expect(
transform2.rotation,
closeToQuaternion(Quaternion(0.1, 0.2, 0.3, 0.4).normalized(), epsilon),
);
expect(transform2.scale, closeToVector3(Vector3.all(1), epsilon));

final matrix3 = Transform3D.matrix4(
scale: Vector3(4, 5, 6),
);
final transform3 = Transform3D()..setFromMatrix4(matrix3);
expect(transform3.position, closeToVector3(Vector3.zero(), epsilon));
expect(
transform3.rotation,
closeToQuaternion(Quaternion.identity(), epsilon),
);
expect(transform3.scale, closeToVector3(Vector3(4, 5, 6), epsilon));
});
});
}

0 comments on commit 09c28ca

Please sign in to comment.