let background;
let speed = 0.5;

class Example extends Phaser.Scene {
  preload() {
    // Source : https://vnitti.itch.io/glacial-mountains-parallax-background
    this.load.image(
      "background",
      "https://assets.codepen.io/9367036/clouds_bg_1.png"
    );
    // Source : https://gandalfhardcore.itch.io/free-pixel-art
    this.load.spritesheet(
      "warrior",
      "https://assets.codepen.io/9367036/GandalfHardcore+Warrior.png",
      {
        frameWidth: 80,
        frameHeight: 64
      }
    );
  }

  create() {
    background = this.add.tileSprite(
      0,
      0,
      config.width * 1.1, // bug fix
      216,
      "background"
    );
    background.setOrigin(0, 1);

    this.anims.create({
      key: "idle",
      frames: this.anims.generateFrameNumbers("warrior", {
        start: 0,
        end: 4
      }),
      frameRate: 10,
      repeat: -1
    });

    this.anims.create({
      key: "walk",
      frames: this.anims.generateFrameNumbers("warrior", {
        start: 10,
        end: 17
      }),
      frameRate: 10,
      repeat: -1
    });

    this.anims.create({
      key: "run",
      frames: this.anims.generateFrameNumbers("warrior", {
        start: 20,
        end: 27
      }),
      frameRate: 10,
      repeat: -1
    });

    this.player = this.physics.add
      .sprite(0, 0, "player")
      .setScale(2)
      .setOrigin(0.5, 1)
      .setFlipX(true)
      .play("walk");

    this.player.body.setSize(this.player.width, this.player.height);
    this.player.body.setOffset(0, 0);

    this.cameras.main.startFollow(
      this.player,
      false,
      1,
      1,
      0,
      config.height / 2.125
    );
    this.cameras.main.setBackgroundColor("#9C2E2E");

    background.y = this.cameras.main.scrollY + config.height;
  }

  update(time) {
    speed = (Math.sin(time / 1200) + 1) / 2;
    this.player.setVelocityX(speed * 500);
    background.tilePositionX += speed * 5;
    background.x = this.cameras.main.scrollX;

    if (speed < 0.05) {
      if (
        this.player.anims.currentAnim &&
        this.player.anims.currentAnim.key !== "idle"
      ) {
        this.player.play("idle");
      }
    } else if (speed >= 0.05 && speed < 0.75) {
      if (
        this.player.anims.currentAnim &&
        this.player.anims.currentAnim.key !== "walk"
      ) {
        this.player.play("walk");
      }
    } else {
      if (
        this.player.anims.currentAnim &&
        this.player.anims.currentAnim.key !== "run"
      ) {
        this.player.play("run");
      }
    }
  }
}

const config = {
  width: 800,
  height: 200,
  pixelArt: true,
  scene: Example,
  physics: {
    default: "arcade",
    arcade: {
      debug: true
    }
  }
};

const game = new Phaser.Game(config);

External CSS

  1. https://codepen.io/tim-momo/pen/yLWvyra.css

External JavaScript

  1. https://cdnjs.cloudflare.com/ajax/libs/phaser/3.85.1/phaser.min.js