Line data Source code
1 : import 'dart:ui';
2 :
3 : import '../../extensions.dart';
4 : import '../../game.dart';
5 : import '../../geometry.dart';
6 : import 'shape.dart';
7 :
8 : class Rectangle extends Polygon {
9 18 : static final _defaultNormalizedVertices = [
10 6 : Vector2(1, 1),
11 6 : Vector2(1, -1),
12 6 : Vector2(-1, -1),
13 6 : Vector2(-1, 1),
14 : ];
15 :
16 2 : Rectangle({
17 : Vector2? position,
18 : Vector2? size,
19 : double angle = 0,
20 2 : }) : super.fromDefinition(
21 2 : _defaultNormalizedVertices,
22 : position: position,
23 : size: size,
24 : angle: angle,
25 : );
26 :
27 : /// This constructor is used by [HitboxRectangle] and is most often not useful
28 : /// for any other cases.
29 : /// The [relation] describes the relationship between x and y and the size of
30 : /// the rectangle, both x and y in [relation] should be less or equal to 1.0
31 : /// if this should be used for collision detection.
32 : ///
33 : /// For example if the [size] is (100, 100) and the [relation] is (0.5, 1.0)
34 : /// the it will represent a rectangle with the points (25, 50), (25, -50),
35 : /// (-25, -50) and (-25, 50) because the rectangle is defined from the center
36 : /// of itself. The [position] will therefore be the center of the Rectangle.
37 : ///
38 : /// If you want to create the [Rectangle] from a positioned [Rect] instead,
39 : /// have a look at [Rectangle.fromRect].
40 6 : Rectangle.fromDefinition({
41 : Vector2? relation,
42 : Vector2? position,
43 : Vector2? size,
44 : double angle = 0,
45 6 : }) : super.fromDefinition(
46 : relation != null
47 3 : ? [
48 3 : relation.clone(),
49 12 : Vector2(relation.x, -relation.y),
50 3 : -relation,
51 12 : Vector2(-relation.x, relation.y),
52 : ]
53 4 : : _defaultNormalizedVertices,
54 : position: position,
55 : size: size,
56 : angle: angle,
57 : );
58 :
59 : /// With this helper method you can create your [Rectangle] from a positioned
60 : /// [Rect] instead of percentages. This helper will also calculate the size
61 : /// and center of the [Rectangle].
62 4 : factory Rectangle.fromRect(
63 : Rect rect, {
64 : double angle = 0,
65 : }) {
66 4 : return Rectangle.fromDefinition(
67 8 : position: rect.center.toVector2(),
68 8 : size: rect.size.toVector2(),
69 : angle: angle,
70 : );
71 : }
72 : }
73 :
74 : class HitboxRectangle extends Rectangle with HitboxShape {
75 3 : HitboxRectangle({Vector2? relation})
76 3 : : super.fromDefinition(
77 3 : relation: relation ?? Vector2.all(1),
78 : );
79 : }
|