Create a parallax background in Flame com Flutter
Parallax backgrounds are used in all kinds of applications, not only in 2D games, but also in web pages to define background, etc; In this post we will see how to define a parallax background as background for our 2D games with Flame.
Let's start by loading the images for the parallax background:
In Flame, we have a component called ParallaxComponent that makes the process of creating a parallax effect very easy; with defining the images to use as a list:
lib/main.dart
class MyGame extends FlameGame {
@override
void onLoad() async {
super.onLoad();
add(await bgParallax());
}
Future<ParallaxComponent> bgParallax() async {
ParallaxComponent parallaxComponent = await loadParallaxComponent([
ParallaxImageData('layer06_sky.png'),
ParallaxImageData('layer05_rocks.png'),
ParallaxImageData('layer04_clouds.png'),
ParallaxImageData('layer03_trees.png'),
ParallaxImageData('layer02_cake.png'),
ParallaxImageData('layer01_ground.png'),
],
baseVelocity: Vector2(10, 0));
return parallaxComponent;
}
}
You will see that we have almost achieved the parallax effect, for now, all the layers move at the same speed; the baseVelocity argument allows you to define the displacement of the backgrounds, usually you want the displacement to occur on the X axis and not on the Y axis, so:
baseVelocity: Vector2(10, 0)
As homework, try different values when defining the vector and using different images (comment out and dislike some of the ParallaxImageData defined above, change the order layers) and evaluate their behavior; but, in essence, if you use high values, such as:
baseVelocity: Vector2(100, 0)
You will see a rapid displacement in the backgrounds, if you place lower values:
baseVelocity: Vector2(5, 0)
The scroll will be slower, and if you define the scroll on the Y:
baseVelocity: Vector2(5, 10)
The layers will move on the X and Y axis.
When you run the application, you should see output like the following: