Drag Events¶
Drag events occur when the user moves their finger across the screen of the device, or when they move the mouse while holding its button down.
Multiple drag events can occur at the same time, if the user is using multiple fingers. Such cases
will be handled correctly by Flame, and you can even keep track of the events by using their
pointerId
property.
For those components that you want to respond to drags, add the DragCallbacks
mixin.
This mixin adds four overridable methods to your component:
onDragStart
,onDragUpdate
,onDragEnd
, andonDragCancel
. By default, these methods do nothing – they need to be overridden in order to perform any function.In addition, the component must implement the
containsLocalPoint()
method (already implemented inPositionComponent
, so most of the time you don’t need to do anything here) – this method allows Flame to know whether the event occurred within the component or not.
class MyComponent extends PositionComponent with DragCallbacks {
MyComponent() : super(size: Vector2(180, 120));
@override
void onDragStart(DragStartEvent event) {
// Do something in response to a drag event
}
}
Demo¶
In this example you can use drag gestures to either drag star-like shapes across the screen, or to draw curves inside the magenta rectangle.
1import 'dart:math';
2
3import 'package:flame/components.dart';
4import 'package:flame/events.dart';
5import 'package:flame/game.dart';
6import 'package:flame/geometry.dart';
7import 'package:flutter/rendering.dart';
8
9class DragEventsGame extends FlameGame {
10 @override
11 Future<void> onLoad() async {
12 addAll([
13 DragTarget(),
14 Star(
15 n: 5,
16 radius1: 40,
17 radius2: 20,
18 sharpness: 0.2,
19 color: const Color(0xffbae5ad),
20 position: Vector2(70, 70),
21 ),
22 Star(
23 n: 3,
24 radius1: 50,
25 radius2: 40,
26 sharpness: 0.3,
27 color: const Color(0xff6ecbe5),
28 position: Vector2(70, 160),
29 ),
30 Star(
31 n: 12,
32 radius1: 10,
33 radius2: 75,
34 sharpness: 1.3,
35 color: const Color(0xfff6df6a),
36 position: Vector2(70, 270),
37 ),
38 Star(
39 n: 10,
40 radius1: 20,
41 radius2: 17,
42 sharpness: 0.85,
43 color: const Color(0xfff82a4b),
44 position: Vector2(110, 110),
45 ),
46 ]);
47 }
48}
49
50/// This component is the pink-ish rectangle in the center of the game window.
51/// It uses the [DragCallbacks] mixin in order to receive drag events.
52class DragTarget extends PositionComponent with DragCallbacks {
53 DragTarget() : super(anchor: Anchor.center);
54
55 final _rectPaint = Paint()..color = const Color(0x88AC54BF);
56
57 /// We will store all current circles into this map, keyed by the `pointerId`
58 /// of the event that created the circle.
59 final Map<int, Trail> _trails = {};
60
61 @override
62 void onGameResize(Vector2 size) {
63 super.onGameResize(size);
64 this.size = size - Vector2(100, 75);
65 if (this.size.x < 100 || this.size.y < 100) {
66 this.size = size * 0.9;
67 }
68 position = size / 2;
69 }
70
71 @override
72 void render(Canvas canvas) {
73 canvas.drawRect(size.toRect(), _rectPaint);
74 }
75
76 @override
77 void onDragStart(DragStartEvent event) {
78 super.onDragStart(event);
79 final trail = Trail(event.localPosition);
80 _trails[event.pointerId] = trail;
81 add(trail);
82 }
83
84 @override
85 void onDragUpdate(DragUpdateEvent event) {
86 _trails[event.pointerId]!.addPoint(event.localEndPosition);
87 }
88
89 @override
90 void onDragEnd(DragEndEvent event) {
91 super.onDragEnd(event);
92 _trails.remove(event.pointerId)!.end();
93 }
94
95 @override
96 void onDragCancel(DragCancelEvent event) {
97 super.onDragCancel(event);
98 _trails.remove(event.pointerId)!.cancel();
99 }
100}
101
102class Trail extends Component {
103 Trail(Vector2 origin)
104 : _paths = [Path()..moveTo(origin.x, origin.y)],
105 _opacities = [1],
106 _lastPoint = origin.clone(),
107 _color =
108 HSLColor.fromAHSL(1, random.nextDouble() * 360, 1, 0.8).toColor();
109
110 final List<Path> _paths;
111 final List<double> _opacities;
112 Color _color;
113 late final _linePaint = Paint()..style = PaintingStyle.stroke;
114 late final _circlePaint = Paint()..color = _color;
115 bool _released = false;
116 double _timer = 0;
117 final _vanishInterval = 0.03;
118 final Vector2 _lastPoint;
119
120 static final random = Random();
121 static const lineWidth = 10.0;
122
123 @override
124 void render(Canvas canvas) {
125 assert(_paths.length == _opacities.length);
126 for (var i = 0; i < _paths.length; i++) {
127 final path = _paths[i];
128 final opacity = _opacities[i];
129 if (opacity > 0) {
130 _linePaint.color = _color.withOpacity(opacity);
131 _linePaint.strokeWidth = lineWidth * opacity;
132 canvas.drawPath(path, _linePaint);
133 }
134 }
135 canvas.drawCircle(
136 _lastPoint.toOffset(),
137 (lineWidth - 2) * _opacities.last + 2,
138 _circlePaint,
139 );
140 }
141
142 @override
143 void update(double dt) {
144 assert(_paths.length == _opacities.length);
145 _timer += dt;
146 while (_timer > _vanishInterval) {
147 _timer -= _vanishInterval;
148 for (var i = 0; i < _paths.length; i++) {
149 _opacities[i] -= 0.01;
150 if (_opacities[i] <= 0) {
151 _paths[i].reset();
152 }
153 }
154 if (!_released) {
155 _paths.add(Path()..moveTo(_lastPoint.x, _lastPoint.y));
156 _opacities.add(1);
157 }
158 }
159 if (_opacities.last < 0) {
160 removeFromParent();
161 }
162 }
163
164 void addPoint(Vector2 point) {
165 if (!point.x.isNaN) {
166 for (final path in _paths) {
167 path.lineTo(point.x, point.y);
168 }
169 _lastPoint.setFrom(point);
170 }
171 }
172
173 void end() => _released = true;
174
175 void cancel() {
176 _released = true;
177 _color = const Color(0xFFFFFFFF);
178 }
179}
180
181class Star extends PositionComponent with DragCallbacks {
182 Star({
183 required int n,
184 required double radius1,
185 required double radius2,
186 required double sharpness,
187 required this.color,
188 super.position,
189 }) {
190 _path = Path()..moveTo(radius1, 0);
191 for (var i = 0; i < n; i++) {
192 final p1 = Vector2(radius2, 0)..rotate(tau / n * (i + sharpness));
193 final p2 = Vector2(radius2, 0)..rotate(tau / n * (i + 1 - sharpness));
194 final p3 = Vector2(radius1, 0)..rotate(tau / n * (i + 1));
195 _path.cubicTo(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y);
196 }
197 _path.close();
198 }
199
200 final Color color;
201 final Paint _paint = Paint();
202 final Paint _borderPaint = Paint()
203 ..color = const Color(0xFFffffff)
204 ..style = PaintingStyle.stroke
205 ..strokeWidth = 3;
206 final _shadowPaint = Paint()
207 ..color = const Color(0xFF000000)
208 ..maskFilter = const MaskFilter.blur(BlurStyle.normal, 4.0);
209 late final Path _path;
210
211 @override
212 bool containsLocalPoint(Vector2 point) {
213 return _path.contains(point.toOffset());
214 }
215
216 @override
217 void render(Canvas canvas) {
218 if (isDragged) {
219 _paint.color = color.withOpacity(0.5);
220 canvas.drawPath(_path, _paint);
221 canvas.drawPath(_path, _borderPaint);
222 } else {
223 _paint.color = color.withOpacity(1);
224 canvas.drawPath(_path, _shadowPaint);
225 canvas.drawPath(_path, _paint);
226 }
227 }
228
229 @override
230 void onDragStart(DragStartEvent event) {
231 super.onDragStart(event);
232 priority = 10;
233 }
234
235 @override
236 void onDragEnd(DragEndEvent event) {
237 super.onDragEnd(event);
238 priority = 0;
239 }
240
241 @override
242 void onDragUpdate(DragUpdateEvent event) {
243 position += event.localDelta;
244 }
245}
Drag anatomy¶
onDragStart¶
This is the first event that occurs in a drag sequence. Usually, the event will be delivered to the
topmost component at the point of touch with the DragCallbacks
mixin. However, by setting the flag
event.continuePropagation
to true, you can allow the event to propagate to the components below.
The DragStartEvent
object associated with this event will contain the coordinate of the point
where the event has originated. This point is available in multiple coordinate system:
devicePosition
is given in the coordinate system of the entire device, canvasPosition
is in the
coordinate system of the game widget, and localPosition
provides the position in the component’s
local coordinate system.
Any component that receives onDragStart
will later be receiving onDragUpdate
and onDragEnd
events as well.
onDragUpdate¶
This event is fired continuously as user drags their finger across the screen. It will not fire if the user is holding their finger still.
The default implementation delivers this event to all the components that received the previous
onDragStart
with the same pointer id. If the point of touch is still within the component, then
event.localPosition
will give the position of that point in the local coordinate system. However,
if the user moves their finger away from the component, the property event.localPosition
will
return a point whose coordinates are NaNs. Likewise, the event.renderingTrace
in this case will be
empty. However, the canvasPosition
and devicePosition
properties of the event will be valid.
In addition, the DragUpdateEvent
will contain delta
– the amount the finger has moved since the
previous onDragUpdate
, or since the onDragStart
if this is the first drag-update after a drag-
start.
The event.timestamp
property measures the time elapsed since the beginning of the drag. It can be
used, for example, to compute the speed of the movement.
onDragEnd¶
This event is fired when the user lifts their finger and thus stops the drag gesture. There is no position associated with this event.
onDragCancel¶
The precise semantics when this event occurs is not clear, so we provide a default implementation
which simply converts this event into an onDragEnd
.
Mixins¶
DragCallbacks¶
The DragCallbacks
mixin can be added to any Component
in order for that component to start
receiving drag events.
This mixin adds methods onDragStart
, onDragUpdate
, onDragEnd
, and onDragCancel
to the
component, which by default don’t do anything, but can be overridden to implement any real
functionality.
Another crucial detail is that a component will only receive drag events that originate within
that component, as judged by the containsLocalPoint()
function. The commonly-used
PositionComponent
class provides such an implementation based on its size
property. Thus, if
your component derives from a PositionComponent
, then make sure that you set its size correctly.
If, however, your component derives from the bare Component
, then the containsLocalPoint()
method must be implemented manually.
If your component is a part of a larger hierarchy, then it will only receive drag events if its
ancestors have all implemented the containsLocalPoint
correctly.
class MyComponent extends PositionComponent with DragCallbacks {
MyComponent({super.size});
final _paint = Paint();
bool _isDragged = false;
@override
void onDragStart(DragStartEvent event) => _isDragged = true;
@override
void onDragUpdate(DragUpdateEvent event) => position += event.delta;
@override
void onDragEnd(DragEndEvent event) => _isDragged = false;
@override
void render(Canvas canvas) {
_paint.color = _isDragged? Colors.red : Colors.white;
canvas.drawRect(size.toRect(), _paint);
}
}