[SOLVED]How to play/add an animated background

How can I use this spritesheet has an animated background image?
My main goal is to change every 2 seconds, the frame, but so far I’m having trouble doing this because my frame is changing so quickly …

   export default class DeadScene extends Phaser.Scene {
    constructor(key) {
        super(key);
    }

    preload() {
        this.load.image('gameover', 'assets/titlescreen/GameOverScreen.png');
    }
    create() {
        //set background
        this.background1 = this.add.tileSprite(300, 200, 700, 400, "gameover");
    }
    update() {
        this.background1.tilePositionX += 100;
    }

}

I already tried using a timer, but for some reason it was not being activated …

The update method is called every frame, usually 60 times a second. A timer is indeed one of the possible solutions, so it would be nice to see the timer-based code which doesn’t work.

While this is unrelated to your problem, a Tile Sprite (which, as far as I can tell, is supposed to cover the whole screen) might not be the most efficient option in this case. It might be better to use a normal Image with the same texture and change its X position or use a spritesheet and change the frame. I haven’t checked your image in detail, however, so this advice might not be useful.

1 Like

Decided to use a spritesheet and I have succeed it

I did something similar recently.

var iter = 0
var bgSpeed = 0.01

create () {
    bg = this.add.tileSprite(360, 640, 1024, 1024, 'bg')
}

update () {
    // BG
    bg.tilePositionX = Math.fround(iter) * 200
    iter += bgSpeed
}

Perhaps this will help.

Original post I referenced : http://www.html5gamedevs.com/topic/37213-looping-background-image/

1 Like

I already solved the problem, I decided to use a sprite sheet and then make the correct calculations so that the transition of the frames was correct

I will leave the code here:

export default class MenuScene extends Phaser.Scene {
constructor(key) {
    super(key);
}

preload() {
    this.load.spritesheet("background", "assets/titlescreen/GameOverScreen.png", {
        frameHeight: 400,
        frameWidth: 712,
        spacing: 710
    });
}

create() {
    this.anims.create({
        key: "gameover",
        frames: this.anims.generateFrameNumbers("background", {
            start: 0,
            end: 4
        }),
        frameRate: 2,
        repeat: 0
    });

    this.background = this.add.sprite(290, 200, 'gameover');
}

update() {
    this.background.anims.play("gameover", true);
}

But still thanks for the help

2 Likes