I was able to create a particle that shows text when tapped using the code below. Is it possible to make this particle fade out? (in this question, by "fade out," I mean adjusting the opacity.)
import 'package:flame/components.dart';
import 'package:flame/game.dart';
import 'package:flame/input.dart';
import 'package:flame/particles.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const FooApp());
}
class FooApp extends StatelessWidget {
const FooApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: GameWidget.controlled(gameFactory: TextGame.new),
);
}
}
class TextGame extends FlameGame {
@override
Future<void> onLoad() async {
super.onLoad();
await add(
ButtonComponent(
position: Vector2(size.x * 0.5, size.y * 0.5),
onPressed: () {
add(
ParticleSystemComponent(
position: Vector2(size.x * 0.5, size.y * 0.5),
particle: AcceleratedParticle(
lifespan: 2.0,
speed: Vector2(0, 50),
child: ComponentParticle(
component: TextComponent(
anchor: Anchor.center,
text: "Taped!",
),
),
),
),
);
},
button: TextComponent(
text: 'B',
textRenderer: TextPaint(
style: const TextStyle(
fontSize: 88,
color: Colors.white,
),
),
),
anchor: Anchor.center,
),
);
}
}
References:
Yes! You can implement your own custom particle and use its update method to change the opacity.
For example, you can extend CircleParticle
and provide an implementation to slowly reduce the opacity until it reaches zero.
class MyParticle extends CircleParticle {
MyParticle({required super.paint});
@override
void update(double dt) {
super.update(dt);
final newAlpha = (paint.color.a - 0.5 * dt).clamp(0.0, 1.0);
paint.color = paint.color.withValues(alpha: newAlpha);
}
}
You can also play around with composition with other Particles, using Flutter's Curves for non-linear behaviour, and much more.
As a more complete example, this implementation fires a burst of red particles that then fade out.