I have a list of sprite components in my game that represent three background sprite images which I would like to scroll infinitely. I initialize, update, and render the sprite components using the code below, however the sprites all move at different speeds and the game can slow down immensely at times, what is it that I am doing wrong?
Initializing:
List<SpriteComponent> bkgList = [];
bkgImage = await images.load('BGFull.png');
for (int i = 0; i < MAX_BKG_COUNT; i++) {
final spr = Sprite(bkgImage);
bkgList.add(SpriteComponent(
sprite: spr,
position: Vector2(640.0 * i, 0),
size: Vector2(640, 384)
));
}
Update:
for (int j = 0; j < bkgList.length; j++) {
bkgList[j].position.x -= 1.0;
if (bkgList[j].position.x < -640.0) {
bkgList.removeAt(0);
bkgList.add(SpriteComponent(
sprite: Sprite(bkgImage),
position: Vector2(bkgList.last.position.x + 640.0, 0),
size: Vector2(640, 384)
));
}
}
Render:
for (int z = 0; z < bkgList.length; z++) {
bkgList[z].render(canvas);
}
What you want to do for this is most likely to use the ParallaxComponent
which you can find docs for here. For loading the spritesheet that you have in BGFull.png
you can use the SpriteSheet
class, and then pass in the images from there to the ParallaxComponent
.
But from the code you have right now, the problem could be that you are not doing the initialization in the onLoad
method, but I can't tell from your snippets.