Drag Events¶
Note
This document describes the new drag events API. The old (legacy) approach, which is still supported, is described in Gesture Input.
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:flutter/rendering.dart';
7
8class DragEventsGame extends FlameGame {
9 @override
10 Future<void> onLoad() async {
11 addAll([
12 DragTarget(),
13 Star(
14 n: 5,
15 radius1: 40,
16 radius2: 20,
17 sharpness: 0.2,
18 color: const Color(0xffbae5ad),
19 position: Vector2(70, 70),
20 ),
21 Star(
22 n: 3,
23 radius1: 50,
24 radius2: 40,
25 sharpness: 0.3,
26 color: const Color(0xff6ecbe5),
27 position: Vector2(70, 160),
28 ),
29 Star(
30 n: 12,
31 radius1: 10,
32 radius2: 75,
33 sharpness: 1.3,
34 color: const Color(0xfff6df6a),
35 position: Vector2(70, 270),
36 ),
37 Star(
38 n: 10,
39 radius1: 20,
40 radius2: 17,
41 sharpness: 0.85,
42 color: const Color(0xfff82a4b),
43 position: Vector2(110, 110),
44 ),
45 ]);
46 }
47}
48
49/// This component is the pink-ish rectangle in the center of the game window.
50/// It uses the [DragCallbacks] mixin in order to receive drag events.
51class DragTarget extends PositionComponent with DragCallbacks {
52 DragTarget() : super(anchor: Anchor.center);
53
54 final _rectPaint = Paint()..color = const Color(0x88AC54BF);
55
56 /// We will store all current circles into this map, keyed by the `pointerId`
57 /// of the event that created the circle.
58 final Map<int, Trail> _trails = {};
59
60 @override
61 void onGameResize(Vector2 size) {
62 super.onGameResize(size);
63 this.size = size - Vector2(100, 75);
64 if (this.size.x < 100 || this.size.y < 100) {
65 this.size = size * 0.9;
66 }
67 position = size / 2;
68 }
69
70 @override
71 void render(Canvas canvas) {
72 canvas.drawRect(size.toRect(), _rectPaint);
73 }
74
75 @override
76 void onDragStart(DragStartEvent event) {
77 super.onDragStart(event);
78 final trail = Trail(event.localPosition);
79 _trails[event.pointerId] = trail;
80 add(trail);
81 }
82
83 @override
84 void onDragUpdate(DragUpdateEvent event) {
85 _trails[event.pointerId]!.addPoint(event.localPosition);
86 }
87
88 @override
89 void onDragEnd(DragEndEvent event) {
90 super.onDragEnd(event);
91 _trails.remove(event.pointerId)!.end();
92 }
93
94 @override
95 void onDragCancel(DragCancelEvent event) {
96 super.onDragCancel(event);
97 _trails.remove(event.pointerId)!.cancel();
98 }
99}
100
101class Trail extends Component {
102 Trail(Vector2 origin)
103 : _paths = [Path()..moveTo(origin.x, origin.y)],
104 _opacities = [1],
105 _lastPoint = origin.clone(),
106 _color =
107 HSLColor.fromAHSL(1, random.nextDouble() * 360, 1, 0.8).toColor();
108
109 final List<Path> _paths;
110 final List<double> _opacities;
111 Color _color;
112 late final _linePaint = Paint()..style = PaintingStyle.stroke;
113 late final _circlePaint = Paint()..color = _color;
114 bool _released = false;
115 double _timer = 0;
116 final _vanishInterval = 0.03;
117 final Vector2 _lastPoint;
118
119 static final random = Random();
120 static const lineWidth = 10.0;
121
122 @override
123 void render(Canvas canvas) {
124 assert(_paths.length == _opacities.length);
125 for (var i = 0; i < _paths.length; i++) {
126 final path = _paths[i];
127 final opacity = _opacities[i];
128 if (opacity > 0) {
129 _linePaint.color = _color.withOpacity(opacity);
130 _linePaint.strokeWidth = lineWidth * opacity;
131 canvas.drawPath(path, _linePaint);
132 }
133 }
134 canvas.drawCircle(
135 _lastPoint.toOffset(),
136 (lineWidth - 2) * _opacities.last + 2,
137 _circlePaint,
138 );
139 }
140
141 @override
142 void update(double dt) {
143 assert(_paths.length == _opacities.length);
144 _timer += dt;
145 while (_timer > _vanishInterval) {
146 _timer -= _vanishInterval;
147 for (var i = 0; i < _paths.length; i++) {
148 _opacities[i] -= 0.01;
149 if (_opacities[i] <= 0) {
150 _paths[i].reset();
151 }
152 }
153 if (!_released) {
154 _paths.add(Path()..moveTo(_lastPoint.x, _lastPoint.y));
155 _opacities.add(1);
156 }
157 }
158 if (_opacities.last < 0) {
159 removeFromParent();
160 }
161 }
162
163 void addPoint(Vector2 point) {
164 if (!point.x.isNaN) {
165 for (final path in _paths) {
166 path.lineTo(point.x, point.y);
167 }
168 _lastPoint.setFrom(point);
169 }
170 }
171
172 void end() => _released = true;
173
174 void cancel() {
175 _released = true;
176 _color = const Color(0xFFFFFFFF);
177 }
178}
179
180class Star extends PositionComponent with DragCallbacks {
181 Star({
182 required int n,
183 required double radius1,
184 required double radius2,
185 required double sharpness,
186 required this.color,
187 super.position,
188 }) {
189 _path = Path()..moveTo(radius1, 0);
190 for (var i = 0; i < n; i++) {
191 final p1 = Vector2(radius2, 0)..rotate(tau / n * (i + sharpness));
192 final p2 = Vector2(radius2, 0)..rotate(tau / n * (i + 1 - sharpness));
193 final p3 = Vector2(radius1, 0)..rotate(tau / n * (i + 1));
194 _path.cubicTo(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y);
195 }
196 _path.close();
197 }
198
199 final Color color;
200 final Paint _paint = Paint();
201 final Paint _borderPaint = Paint()
202 ..color = const Color(0xFFffffff)
203 ..style = PaintingStyle.stroke
204 ..strokeWidth = 3;
205 final _shadowPaint = Paint()
206 ..color = const Color(0xFF000000)
207 ..maskFilter = const MaskFilter.blur(BlurStyle.normal, 4.0);
208 late final Path _path;
209
210 @override
211 bool containsLocalPoint(Vector2 point) {
212 return _path.contains(point.toOffset());
213 }
214
215 @override
216 void render(Canvas canvas) {
217 if (isDragged) {
218 _paint.color = color.withOpacity(0.5);
219 canvas.drawPath(_path, _paint);
220 canvas.drawPath(_path, _borderPaint);
221 } else {
222 _paint.color = color.withOpacity(1);
223 canvas.drawPath(_path, _shadowPaint);
224 canvas.drawPath(_path, _paint);
225 }
226 }
227
228 @override
229 void onDragStart(DragStartEvent event) {
230 super.onDragStart(event);
231 priority = 10;
232 }
233
234 @override
235 void onDragEnd(DragEndEvent event) {
236 super.onDragEnd(event);
237 priority = 0;
238 }
239
240 @override
241 void onDragUpdate(DragUpdateEvent event) {
242 position += event.delta;
243 }
244}
245
246const tau = 2 * pi;
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);
}
}
HasDraggablesBridge¶
This marker mixin can be used to indicate that the game has both the “new-style” components that
use the DragCallbacks
mixin, and the “old-style” components that use the Draggable
mixin. In
effect, every drag event will be propagated twice through the system: first trying to reach the
components with DragCallbacks
mixin, and then components with Draggable
.
class MyGame extends FlameGame with HasDraggablesBridge {
// ...
}
The purpose of this mixin is to ease the transition from the old event delivery system to the
new one. With this mixin, you can transition your Draggable
components into using DragCallbacks
one by one, verifying that your game continues to work at every step.
Use of this mixin for any new project is highly discouraged.