Phaser won't render assets in React app but no problem outside of React

19 views Asked by At

I've integrated Phaser into React app. I'm facing difficulty rendering assets though. Assets render just fine outside of React application with server and template rendered but getting error when I use it with React.

Home.jsx:

import React from 'react';
import Phaser from 'phaser';
import GameComponent from './GameComponent';


class MyGame extends Phaser.Scene {
    
    preload() {
        this.load.image('bg1', './assets/bgs/bg1.png');
        this.load.image('field', './assets/field.png');
        this.load.image('char', './assets/characters/woman.png');
        
    }

    create() {
        this.add.image(0, 0, 'bg1').setOrigin(0, 0);
        
    }
}
    
const Home = () => {
    const config = {
        type: Phaser.AUTO,
        scene: [MyGame],
        parent: 'phaser-container',
        scale: {
            mode: Phaser.Scale.ScaleModes.RESIZE,
            width: window.innerWidth,
            height: window.innerHeight
        },
        physics: {
            default: 'arcade',
            arcade: {
                gravity: {y: 200},
            },
        },
    };
    return <div><GameComponent config={config} /></div>
}

export default Home;

index.html :

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/phaser-arcade-physics.min.js"></script>
    <title>Family Trip</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
</body>
</html>

Directory structure:

enter image description here

Console output:

enter image description here

Any suggestion as to why React has trouble loading the assets ?

1

There are 1 answers

0
appdeveloper On

Phaser integrated into React looks for assets in the /public/assets directory by default. Moving the assets directory into /public fixed the issue.

Found solution here: https://github.com/phaserjs/template-react