We will see step by step how to create a parallax background using Flame for 2D game development.
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:
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:
Vary speed in layers
At the moment we get a somewhat boring parallax background since, although we have a background that moves, everything moves at the same speed; but, to customize this aspect, that is, that the backgrounds move at different speeds, we can use the velocityMultiplierDelta parameter, which allows moving the background images (layers) with a faster speed, the more "close" the image is image:
With this, we will have the same effect but now the layers move at different speeds; so that you understand how this argument works, try placing higher values and you will see that the closer the layer is, the faster it will move.
Create a component class for the parallax
We can create the parallax equivalent with a component class looking like: