I have a sprite component that I would like to set as the main background of the Flame game and move an avatar on top of this, with CameraComponent following this avatar. Sprite movements that need to be supported are up, down, left and right. As I needed all these movement directions supported, I could not rely just on ParallaxComponent, which seems like a good choice for side-scrolling games.
Problem I am running into is with placement of the sprite background. If I set it using camera.backdrop, the camera.follow(avatar) doesn't move the camera. Following is the relevant code that I have tried so far in my onLoad() method:
@override
Future<void> onLoad() async {
super.onLoad();
_avatar.position = size / 2;
camera.viewport = FixedSizeViewport(size.x, size.y);
camera.follow(_avatar);
await world.add(_map);
await world.add(_avatar);
}
I have tried to set camera.backdrop to the background sprite component (_map); but it doesn't allow camera to move with the _avatar. I am able to set the position of this background sprite component like this - _map.position = Vector2(-size.x, -size.y); But, this paints a black border around the background. I tried to define the camera viewport to control by setting it this way - camera.viewport = FixedSizeViewport(size.x, size.y); However, this doesn't seem to change that black border much.
Below is an image of how my game renders with the above code.
What is the most optimal way to set background image for Flame based games, when we need the camera to follow an avatar that can move in any direction on this background?
Add the background as the first component to your world
and then you add the player to the world too, then you can have the camera following the player when it is moving in the world. (You can also set the priority
of the background to be lower than the priority of the player)
You can set bounds to the camera with camera.setBounds
. Set the bounds to match where the background is in your world.
camera.backdrop
is meant for having a static background meanwhile you move around in the world, that was why that solution did not work for you.