Home > Blockchain >  How to display the Phaser Game Screen only in a Route React?
How to display the Phaser Game Screen only in a Route React?

Time:12-31

I want that my game screen only been displayed in '/game' route, but when I give the boot with method "new Phaser.Game(config)" he start shows in every route '/home', default rote '/', '/error', '/game' and etc.

game.js

import Phaser from 'phaser';
import LoadScene from './scenes/LoadScene.js';
import MenuScene from './scenes/MenuScene.js';

export const config = {
  type: Phaser.AUTO,
  width: 800,
  height: 600,
  scene: [ MenuScene, LoadScene]
};

const game = new Phaser.Game(config);

gamepage.js

import config from '../../phaser/game.js';
import React from 'react';

export default class GamePage extends React.Component {
    render() {
        return <>
            <Game />
        </>;
    }
}

routes.js

import React from 'react';
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import ErrorPage from '../pages/error/index.js';
import Home from '../pages/home/index.js';
import GamePage from '../pages/game/index.js';

export default class Rotas extends React.Component {
    render() {
        return <>
            <Router>
                <Routes>
                    <Route path="/" element={<Home />} />
                    <Route path="/game" elememnt={<GamePage />} />
                    <Route path="*" element={<ErrorPage />} />
                </Routes>
            </Router>
        </>
    };
}

CodePudding user response:

The config object in new Phaser.Game(config); accepts a parent option, which specifies the element that will contain the game canvas. If it is undefined then it will be included in the document body (your case).

You can specify null so that it is not included anywhere, and you are responsible for adding it to the DOM.

See https://newdocs.phaser.io/docs/3.55.2/Phaser.Types.Core.GameConfig#GameConfig for the available options.

You can also have a look at How to integrate Phaser into React as they use that approach

  • Related