Search code examples
javascriptimagepngphaser-framework

Text/Image Phaser 3 render issue


I am new to Phaser 3. I have an issue where when I run my game on a local host the text appears but the image does not. I have tried doing multiple things to get the image to load changing the folder routes, changing the folder in relation to the src folder, renaming the png, making sure the path is correct, making sure the tag is correct, trying other pngs. The dev tools show no errors in the browser. I am using parcel as my bundler not sure if that is the issue. Here are screenshots of my folder structure and what the browser looks like. Any ideas as to what I am doing wrong?

main.js

const Phaser= require('phaser');
const Game= require ("../src/scenes/Game")
  var config = {
    width: 800,
    height: 500,
    type: Phaser.AUTO,
   };
var game = new Phaser.Game(config);
game.scene.add("game", Game);
game.scene.start("game");`

Game.js

const Phaser = require("phaser");
class Game extends Phaser.Scene {
   preload() {
   this.load.image("wind", "../assets/Wind.png");
   }
   create() {
   const text = this.add.text(400, 250, "hello world");
   text.setOrigin(0.5, 0.5);
   this.add.image(400, 250, "wind");
   }
}

module.exports = Game;

index.html

<html>
  <head>
   <title>A Storm's a Brewin</title>
  </head>
<body>
  <script src="./main.js"></script>
</body>`

package.json

    {
  "name": "stormbrewer",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "parcel src/index.html",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "parcel-bundler": "^1.12.5",
    "phaser": "^3.54.0"
  }
}

Folder Structure

What the browser looks like


Solution

  • When you write this.load.image("wind", "../assets/Wind.png"), that path is relative to the position of the file that is loaded by the browser.

    The browser loads the file (usually) from the dist folder, not directly from the src.

    I think you can solve by changing assets folder and telling Parcel how to pack your assets so that xxx/assets will be in dist/assets.

    I usually use parcel-plugin-static-files-copy, and create a public folder along with src and put this in package.json

    ...
    "staticFiles": {
      "staticPath": "public"
    },
    ...
    

    Folder structure

    package.json
    public
    | assets
    | | any.png
    src
    | Game.js
    

    Another solution could be to change how you reference the files that you "give" to Phaser (maybe with a require(...) or something). I know it's somehow possible but the first solution it's enough for my purposes so I didn't dig enough to explain it, but I think it's worth mention it.