⚠ This article covers a previous version of Simple Animation. The basics stay the same but class names have changed.
This was an exciting week with Google I/O. My Flutter package Simple Animations was proofed to be Flutter Web ready and the particle background demo (article) made it into to the official Flutter web samples.
Today I want to write about using a particle system along with user interaction because it was requested one reader.
Basically it’s some cheap “whack-a-mole” implementation in Flutter. Virtual moles appear for a short duration at 6 different places. When you click one mole it will split into multiple particles. After a random time they respawn again. So basically it’s just a simple reaction game.
A mole widget
Let’s start by showing you some (simplified) code of the mole widget:
For the mole we use a Container that is wrapped into a GestureDetector to route user taps into a
_hitMole() method. This mole container is inside a Stack along with the particles. We use Dart 2.3 new “ui-as-code” language features to build our stack children. So this might be new to you.
_hitMole() method we hide the mole container and spawn 50 particles of MoleParticle. This class also has a
buildWidget() method to build a small mole particle.
Everything is happening inside a Rendering widget (coming from Simple Animations). It takes a parameter
onTick that we use to handle the particle life cycle. In our
_manageParticleLifecycle() method we remove all particle with a completed animation.
The particle animation
Our particle animation starts by overlaying the original mole container. Over the time the particle container shrinks to zero while flying into a random direction.
We can implement that behavior into our MoleParticle class:
On particle creation we compute a random target position and store these information into a tween. We use MultiTrackTween (coming from Simple Animations) as we want to tween 3 different properties at once.
Then we create an AnimationProgress (coming from Simple Animations) that keeps track of our animation progress. We just need to feed him with the current time.
Animated tween values and the progress are using inside the
buildWidget() method to draw a positioned and scaled Container.
At the end the we have nice splatter-like animation using a particle system on user interaction.
If you want try hitting a mole yourself then you can instantly download the Example App from Play Store.
You can find my Simple Animations Flutter package on pub.dev and use it for your app. There is a lot of documentation and further examples.
If you like my work leave some claps. Until next time.
— Felix —