├── src
├── styles
│ ├── Home.module.css
│ └── globals.css
├── game
│ ├── EventBus.ts
│ ├── scenes
│ │ ├── Boot.ts
│ │ ├── GameOver.ts
│ │ ├── Game.ts
│ │ ├── Preloader.ts
│ │ └── MainMenu.ts
│ └── main.ts
├── pages
│ ├── _app.tsx
│ ├── _document.tsx
│ └── index.tsx
├── PhaserGame.tsx
└── App.tsx
├── .eslintrc.json
├── screenshot.png
├── public
├── favicon.png
└── assets
│ ├── bg.png
│ ├── logo.png
│ └── star.png
├── next.config.mjs
├── .editorconfig
├── .gitignore
├── tsconfig.json
├── log.js
├── LICENSE
├── package.json
└── README.md
/src/styles/Home.module.css:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/.eslintrc.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "next/core-web-vitals"
3 | }
4 |
--------------------------------------------------------------------------------
/screenshot.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phaserjs/template-nextjs/HEAD/screenshot.png
--------------------------------------------------------------------------------
/public/favicon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phaserjs/template-nextjs/HEAD/public/favicon.png
--------------------------------------------------------------------------------
/public/assets/bg.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phaserjs/template-nextjs/HEAD/public/assets/bg.png
--------------------------------------------------------------------------------
/public/assets/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phaserjs/template-nextjs/HEAD/public/assets/logo.png
--------------------------------------------------------------------------------
/public/assets/star.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phaserjs/template-nextjs/HEAD/public/assets/star.png
--------------------------------------------------------------------------------
/next.config.mjs:
--------------------------------------------------------------------------------
1 | /** @type {import('next').NextConfig} */
2 | const nextConfig = {
3 | output: 'export',
4 | distDir: 'dist'
5 | };
6 |
7 | export default nextConfig;
8 |
--------------------------------------------------------------------------------
/src/game/EventBus.ts:
--------------------------------------------------------------------------------
1 | import { Events } from 'phaser';
2 |
3 | // Used to emit events between components, HTML and Phaser scenes
4 | export const EventBus = new Events.EventEmitter();
--------------------------------------------------------------------------------
/src/pages/_app.tsx:
--------------------------------------------------------------------------------
1 | import "@/styles/globals.css";
2 | import type { AppProps } from "next/app";
3 |
4 | export default function App({ Component, pageProps }: AppProps) {
5 | return ;
6 | }
7 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | # EditorConfig is awesome: https://EditorConfig.org
2 |
3 | # top-most EditorConfig file
4 | root = true
5 |
6 | [*]
7 | indent_style = space
8 | indent_size = 4
9 | end_of_line = crlf
10 | charset = utf-8
11 | trim_trailing_whitespace = false
12 | insert_final_newline = false
--------------------------------------------------------------------------------
/src/pages/_document.tsx:
--------------------------------------------------------------------------------
1 | import { Html, Head, Main, NextScript } from "next/document";
2 |
3 | export default function Document() {
4 | return (
5 |
6 |
8 |
9 |
10 |
11 |
12 | );
13 | }
14 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | /node_modules
5 | /.pnp
6 | .pnp.js
7 | .yarn/install-state.gz
8 |
9 | # testing
10 | /coverage
11 |
12 | # next.js
13 | /.next/
14 | /out/
15 |
16 | # production
17 | /build
18 | /dist
19 |
20 | # misc
21 | .DS_Store
22 | *.pem
23 |
24 | # debug
25 | npm-debug.log*
26 | yarn-debug.log*
27 | yarn-error.log*
28 |
29 | # local env files
30 | .env*.local
31 |
32 | # vercel
33 | .vercel
34 |
35 | # typescript
36 | *.tsbuildinfo
37 | next-env.d.ts
38 |
--------------------------------------------------------------------------------
/src/game/scenes/Boot.ts:
--------------------------------------------------------------------------------
1 | import { Scene } from 'phaser';
2 |
3 | export class Boot extends Scene
4 | {
5 | constructor ()
6 | {
7 | super('Boot');
8 | }
9 |
10 | preload ()
11 | {
12 | // The Boot Scene is typically used to load in any assets you require for your Preloader, such as a game logo or background.
13 | // The smaller the file size of the assets, the better, as the Boot Scene itself has no preloader.
14 |
15 | this.load.image('background', 'assets/bg.png');
16 | }
17 |
18 | create ()
19 | {
20 | this.scene.start('Preloader');
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "lib": [
4 | "dom",
5 | "dom.iterable",
6 | "esnext"
7 | ],
8 | "allowJs": true,
9 | "skipLibCheck": true,
10 | "strict": true,
11 | "noEmit": true,
12 | "esModuleInterop": true,
13 | "module": "esnext",
14 | "moduleResolution": "bundler",
15 | "resolveJsonModule": true,
16 | "isolatedModules": true,
17 | "jsx": "preserve",
18 | "incremental": true,
19 | "strictPropertyInitialization": false,
20 | "paths": {
21 | "@/*": [
22 | "./src/*"
23 | ]
24 | },
25 | "target": "ES2017"
26 | },
27 | "include": [
28 | "next-env.d.ts",
29 | "**/*.ts",
30 | "**/*.tsx"
31 | ],
32 | "exclude": [
33 | "node_modules"
34 | ]
35 | }
36 |
--------------------------------------------------------------------------------
/src/game/main.ts:
--------------------------------------------------------------------------------
1 | import { Boot } from './scenes/Boot';
2 | import { GameOver } from './scenes/GameOver';
3 | import { Game as MainGame } from './scenes/Game';
4 | import { MainMenu } from './scenes/MainMenu';
5 | import { AUTO, Game } from 'phaser';
6 | import { Preloader } from './scenes/Preloader';
7 |
8 | // Find out more information about the Game Config at:
9 | // https://newdocs.phaser.io/docs/3.70.0/Phaser.Types.Core.GameConfig
10 | const config: Phaser.Types.Core.GameConfig = {
11 | type: AUTO,
12 | width: 1024,
13 | height: 768,
14 | parent: 'game-container',
15 | backgroundColor: '#028af8',
16 | scene: [
17 | Boot,
18 | Preloader,
19 | MainMenu,
20 | MainGame,
21 | GameOver
22 | ]
23 | };
24 |
25 | const StartGame = (parent: string) => {
26 |
27 | return new Game({ ...config, parent });
28 |
29 | }
30 |
31 | export default StartGame;
32 |
--------------------------------------------------------------------------------
/src/pages/index.tsx:
--------------------------------------------------------------------------------
1 | import Head from "next/head";
2 | import { Inter } from "next/font/google";
3 | import styles from "@/styles/Home.module.css";
4 | import dynamic from "next/dynamic";
5 |
6 | const inter = Inter({ subsets: ["latin"] });
7 |
8 | const AppWithoutSSR = dynamic(() => import("@/App"), { ssr: false });
9 |
10 | export default function Home() {
11 | return (
12 | <>
13 |
14 | Phaser Nextjs Template
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 | >
23 | );
24 | }
25 |
--------------------------------------------------------------------------------
/log.js:
--------------------------------------------------------------------------------
1 | const fs = require('fs');
2 | const https = require('https');
3 |
4 | const main = async () => {
5 | const args = process.argv.slice(2);
6 | const packageData = JSON.parse(fs.readFileSync('./package.json', 'utf8'));
7 | const event = args[0] || 'unknown';
8 | const phaserVersion = packageData.dependencies.phaser;
9 |
10 | const options = {
11 | hostname: 'gryzor.co',
12 | port: 443,
13 | path: `/v/${event}/${phaserVersion}/${packageData.name}`,
14 | method: 'GET'
15 | };
16 |
17 | try {
18 | const req = https.request(options, (res) => {
19 | res.on('data', () => {});
20 | res.on('end', () => {
21 | process.exit(0);
22 | });
23 | });
24 |
25 | req.on('error', (error) => {
26 | process.exit(1);
27 | });
28 |
29 | req.end();
30 | } catch (error) {
31 | // Silence is the canvas where the soul paints its most profound thoughts.
32 | process.exit(1);
33 | }
34 | }
35 |
36 | main();
37 |
--------------------------------------------------------------------------------
/src/game/scenes/GameOver.ts:
--------------------------------------------------------------------------------
1 | import { EventBus } from '../EventBus';
2 | import { Scene } from 'phaser';
3 |
4 | export class GameOver extends Scene
5 | {
6 | camera: Phaser.Cameras.Scene2D.Camera;
7 | background: Phaser.GameObjects.Image;
8 | gameOverText : Phaser.GameObjects.Text;
9 |
10 | constructor ()
11 | {
12 | super('GameOver');
13 | }
14 |
15 | create ()
16 | {
17 | this.camera = this.cameras.main
18 | this.camera.setBackgroundColor(0xff0000);
19 |
20 | this.background = this.add.image(512, 384, 'background');
21 | this.background.setAlpha(0.5);
22 |
23 | this.gameOverText = this.add.text(512, 384, 'Game Over', {
24 | fontFamily: 'Arial Black', fontSize: 64, color: '#ffffff',
25 | stroke: '#000000', strokeThickness: 8,
26 | align: 'center'
27 | }).setOrigin(0.5).setDepth(100);
28 |
29 | EventBus.emit('current-scene-ready', this);
30 | }
31 |
32 | changeScene ()
33 | {
34 | this.scene.start('MainMenu');
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/game/scenes/Game.ts:
--------------------------------------------------------------------------------
1 | import { EventBus } from '../EventBus';
2 | import { Scene } from 'phaser';
3 |
4 | export class Game extends Scene
5 | {
6 | camera: Phaser.Cameras.Scene2D.Camera;
7 | background: Phaser.GameObjects.Image;
8 | gameText: Phaser.GameObjects.Text;
9 |
10 | constructor ()
11 | {
12 | super('Game');
13 | }
14 |
15 | create ()
16 | {
17 | this.camera = this.cameras.main;
18 | this.camera.setBackgroundColor(0x00ff00);
19 |
20 | this.background = this.add.image(512, 384, 'background');
21 | this.background.setAlpha(0.5);
22 |
23 | this.gameText = this.add.text(512, 384, 'Make something fun!\nand share it with us:\nsupport@phaser.io', {
24 | fontFamily: 'Arial Black', fontSize: 38, color: '#ffffff',
25 | stroke: '#000000', strokeThickness: 8,
26 | align: 'center'
27 | }).setOrigin(0.5).setDepth(100);
28 |
29 | EventBus.emit('current-scene-ready', this);
30 | }
31 |
32 | changeScene ()
33 | {
34 | this.scene.start('GameOver');
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/styles/globals.css:
--------------------------------------------------------------------------------
1 | body {
2 | margin: 0;
3 | padding: 0;
4 | color: rgba(255, 255, 255, 0.87);
5 | background-color: #000000;
6 | font-family: Arial, Helvetica, sans-serif;
7 | }
8 |
9 | #app {
10 | width: 100%;
11 | height: 100vh;
12 | overflow: hidden;
13 | display: flex;
14 | justify-content: center;
15 | align-items: center;
16 | }
17 |
18 | .spritePosition {
19 | margin: 10px 0 0 10px;
20 | font-size: 0.8em;
21 | }
22 |
23 | .button {
24 | width: 140px;
25 | margin: 10px;
26 | padding: 10px;
27 | background-color: #000000;
28 | color: rgba(255, 255, 255, 0.87);
29 | border: 1px solid rgba(255, 255, 255, 0.87);
30 | cursor: pointer;
31 | transition: all 0.3s;
32 |
33 | &:hover {
34 | border: 1px solid #0ec3c9;
35 | color: #0ec3c9;
36 | }
37 |
38 | &:active {
39 | background-color: #0ec3c9;
40 | }
41 |
42 | /* Disabled styles */
43 | &:disabled {
44 | cursor: not-allowed;
45 | border: 1px solid rgba(255, 255, 255, 0.3);
46 | color: rgba(255, 255, 255, 0.3);
47 | }
48 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2025 Phaser
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "template-nextjs",
3 | "version": "1.2.0",
4 | "description": "A Phaser 3 Next.js project template that demonstrates Next.js with React communication and uses Vite for bundling.",
5 | "repository": {
6 | "type": "git",
7 | "url": "git+https://github.com/phaserjs/template-nextjs.git"
8 | },
9 | "author": "Phaser Studio (https://phaser.io/)",
10 | "license": "MIT",
11 | "licenseUrl": "http://www.opensource.org/licenses/mit-license.php",
12 | "bugs": {
13 | "url": "https://github.com/phaserjs/template-nextjs/issues"
14 | },
15 | "homepage": "https://github.com/phaserjs/template-nextjs#readme",
16 | "keywords": [
17 | "phaser",
18 | "phaser3",
19 | "next",
20 | "nextjs",
21 | "vite",
22 | "typescript"
23 | ],
24 | "scripts": {
25 | "dev": "node log.js dev & next dev -p 8080",
26 | "build": "node log.js build & next build",
27 | "dev-nolog": "next dev -p 8080",
28 | "build-nolog": "next build"
29 | },
30 | "dependencies": {
31 | "next": "15.3.1",
32 | "phaser": "^3.90.0",
33 | "react": "19.0.0",
34 | "react-dom": "19.0.0"
35 | },
36 | "devDependencies": {
37 | "@types/node": "^20",
38 | "@types/react": "^19",
39 | "@types/react-dom": "^19",
40 | "typescript": "^5"
41 | }
42 | }
--------------------------------------------------------------------------------
/src/game/scenes/Preloader.ts:
--------------------------------------------------------------------------------
1 | import { Scene } from 'phaser';
2 |
3 | export class Preloader extends Scene
4 | {
5 | constructor ()
6 | {
7 | super('Preloader');
8 | }
9 |
10 | init ()
11 | {
12 | // We loaded this image in our Boot Scene, so we can display it here
13 | this.add.image(512, 384, 'background');
14 |
15 | // A simple progress bar. This is the outline of the bar.
16 | this.add.rectangle(512, 384, 468, 32).setStrokeStyle(1, 0xffffff);
17 |
18 | // This is the progress bar itself. It will increase in size from the left based on the % of progress.
19 | const bar = this.add.rectangle(512-230, 384, 4, 28, 0xffffff);
20 |
21 | // Use the 'progress' event emitted by the LoaderPlugin to update the loading bar
22 | this.load.on('progress', (progress: number) => {
23 |
24 | // Update the progress bar (our bar is 464px wide, so 100% = 464px)
25 | bar.width = 4 + (460 * progress);
26 |
27 | });
28 | }
29 |
30 | preload ()
31 | {
32 | // Load the assets for the game - Replace with your own assets
33 | this.load.setPath('assets');
34 |
35 | this.load.image('logo', 'logo.png');
36 | this.load.image('star', 'star.png');
37 | }
38 |
39 | create ()
40 | {
41 | // When all the assets have loaded, it's often worth creating global objects here that the rest of the game can use.
42 | // For example, you can define global animations here, so we can use them in other scenes.
43 |
44 | // Move to the MainMenu. You could also swap this for a Scene Transition, such as a camera fade.
45 | this.scene.start('MainMenu');
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/game/scenes/MainMenu.ts:
--------------------------------------------------------------------------------
1 | import { GameObjects, Scene } from 'phaser';
2 |
3 | import { EventBus } from '../EventBus';
4 |
5 | export class MainMenu extends Scene
6 | {
7 | background: GameObjects.Image;
8 | logo: GameObjects.Image;
9 | title: GameObjects.Text;
10 | logoTween: Phaser.Tweens.Tween | null;
11 |
12 | constructor ()
13 | {
14 | super('MainMenu');
15 | }
16 |
17 | create ()
18 | {
19 | this.background = this.add.image(512, 384, 'background');
20 |
21 | this.logo = this.add.image(512, 300, 'logo').setDepth(100);
22 |
23 | this.title = this.add.text(512, 460, 'Main Menu', {
24 | fontFamily: 'Arial Black', fontSize: 38, color: '#ffffff',
25 | stroke: '#000000', strokeThickness: 8,
26 | align: 'center'
27 | }).setOrigin(0.5).setDepth(100);
28 |
29 | EventBus.emit('current-scene-ready', this);
30 | }
31 |
32 | changeScene ()
33 | {
34 | if (this.logoTween)
35 | {
36 | this.logoTween.stop();
37 | this.logoTween = null;
38 | }
39 |
40 | this.scene.start('Game');
41 | }
42 |
43 | moveLogo (reactCallback: ({ x, y }: { x: number, y: number }) => void)
44 | {
45 | if (this.logoTween)
46 | {
47 | if (this.logoTween.isPlaying())
48 | {
49 | this.logoTween.pause();
50 | }
51 | else
52 | {
53 | this.logoTween.play();
54 | }
55 | }
56 | else
57 | {
58 | this.logoTween = this.tweens.add({
59 | targets: this.logo,
60 | x: { value: 750, duration: 3000, ease: 'Back.easeInOut' },
61 | y: { value: 80, duration: 1500, ease: 'Sine.easeOut' },
62 | yoyo: true,
63 | repeat: -1,
64 | onUpdate: () => {
65 | if (reactCallback)
66 | {
67 | reactCallback({
68 | x: Math.floor(this.logo.x),
69 | y: Math.floor(this.logo.y)
70 | });
71 | }
72 | }
73 | });
74 | }
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/src/PhaserGame.tsx:
--------------------------------------------------------------------------------
1 | import { forwardRef, useEffect, useLayoutEffect, useRef } from 'react';
2 | import StartGame from './game/main';
3 | import { EventBus } from './game/EventBus';
4 |
5 | export interface IRefPhaserGame
6 | {
7 | game: Phaser.Game | null;
8 | scene: Phaser.Scene | null;
9 | }
10 |
11 | interface IProps
12 | {
13 | currentActiveScene?: (scene_instance: Phaser.Scene) => void
14 | }
15 |
16 | export const PhaserGame = forwardRef(function PhaserGame({ currentActiveScene }, ref)
17 | {
18 | const game = useRef(null!);
19 |
20 | useLayoutEffect(() =>
21 | {
22 | if (game.current === null)
23 | {
24 |
25 | game.current = StartGame("game-container");
26 |
27 | if (typeof ref === 'function')
28 | {
29 | ref({ game: game.current, scene: null });
30 | } else if (ref)
31 | {
32 | ref.current = { game: game.current, scene: null };
33 | }
34 |
35 | }
36 |
37 | return () =>
38 | {
39 | if (game.current)
40 | {
41 | game.current.destroy(true);
42 | if (game.current !== null)
43 | {
44 | game.current = null;
45 | }
46 | }
47 | }
48 | }, [ref]);
49 |
50 | useEffect(() =>
51 | {
52 | EventBus.on('current-scene-ready', (scene_instance: Phaser.Scene) =>
53 | {
54 | if (currentActiveScene && typeof currentActiveScene === 'function')
55 | {
56 |
57 | currentActiveScene(scene_instance);
58 |
59 | }
60 |
61 | if (typeof ref === 'function')
62 | {
63 |
64 | ref({ game: game.current, scene: scene_instance });
65 |
66 | } else if (ref)
67 | {
68 |
69 | ref.current = { game: game.current, scene: scene_instance };
70 |
71 | }
72 |
73 | });
74 | return () =>
75 | {
76 |
77 | EventBus.removeListener('current-scene-ready');
78 |
79 | }
80 | }, [currentActiveScene, ref]);
81 |
82 | return (
83 |
84 | );
85 |
86 | });
87 |
--------------------------------------------------------------------------------
/src/App.tsx:
--------------------------------------------------------------------------------
1 | import { useRef, useState } from 'react';
2 | import { IRefPhaserGame, PhaserGame } from './PhaserGame';
3 | import { MainMenu } from './game/scenes/MainMenu';
4 |
5 | function App()
6 | {
7 | // The sprite can only be moved in the MainMenu Scene
8 | const [canMoveSprite, setCanMoveSprite] = useState(true);
9 |
10 | // References to the PhaserGame component (game and scene are exposed)
11 | const phaserRef = useRef(null);
12 | const [spritePosition, setSpritePosition] = useState({ x: 0, y: 0 });
13 |
14 | const changeScene = () => {
15 |
16 | if(phaserRef.current)
17 | {
18 | const scene = phaserRef.current.scene as MainMenu;
19 |
20 | if (scene)
21 | {
22 | scene.changeScene();
23 | }
24 | }
25 | }
26 |
27 | const moveSprite = () => {
28 |
29 | if(phaserRef.current)
30 | {
31 |
32 | const scene = phaserRef.current.scene as MainMenu;
33 |
34 | if (scene && scene.scene.key === 'MainMenu')
35 | {
36 | // Get the update logo position
37 | scene.moveLogo(({ x, y }) => {
38 |
39 | setSpritePosition({ x, y });
40 |
41 | });
42 | }
43 | }
44 |
45 | }
46 |
47 | const addSprite = () => {
48 |
49 | if (phaserRef.current)
50 | {
51 | const scene = phaserRef.current.scene;
52 |
53 | if (scene)
54 | {
55 | // Add more stars
56 | const x = Phaser.Math.Between(64, scene.scale.width - 64);
57 | const y = Phaser.Math.Between(64, scene.scale.height - 64);
58 |
59 | // `add.sprite` is a Phaser GameObjectFactory method and it returns a Sprite Game Object instance
60 | const star = scene.add.sprite(x, y, 'star');
61 |
62 | // ... which you can then act upon. Here we create a Phaser Tween to fade the star sprite in and out.
63 | // You could, of course, do this from within the Phaser Scene code, but this is just an example
64 | // showing that Phaser objects and systems can be acted upon from outside of Phaser itself.
65 | scene.add.tween({
66 | targets: star,
67 | duration: 500 + Math.random() * 1000,
68 | alpha: 0,
69 | yoyo: true,
70 | repeat: -1
71 | });
72 | }
73 | }
74 | }
75 |
76 | // Event emitted from the PhaserGame component
77 | const currentScene = (scene: Phaser.Scene) => {
78 |
79 | setCanMoveSprite(scene.scene.key !== 'MainMenu');
80 |
81 | }
82 |
83 | return (
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
Sprite Position:
94 |
{`{\n x: ${spritePosition.x}\n y: ${spritePosition.y}\n}`}
95 |
96 |
97 |
98 |
99 |
100 |
101 | )
102 | }
103 |
104 | export default App
105 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Phaser Next.js Template
2 |
3 | This is a Phaser 3 project template that uses the Next.js framework. It includes a bridge for React to Phaser game communication, hot-reloading for quick development workflow and scripts to generate production-ready builds.
4 |
5 | ### Versions
6 |
7 | This template has been updated for:
8 |
9 | - [Phaser 3.90.0](https://github.com/phaserjs/phaser)
10 | - [Next.js 15.3.1](https://github.com/vercel/next.js)
11 | - [TypeScript 5](https://github.com/microsoft/TypeScript)
12 |
13 | 
14 |
15 | ## Requirements
16 |
17 | [Node.js](https://nodejs.org) is required to install dependencies and run scripts via `npm`.
18 |
19 | ## Available Commands
20 |
21 | | Command | Description |
22 | |---------|-------------|
23 | | `npm install` | Install project dependencies |
24 | | `npm run dev` | Launch a development web server |
25 | | `npm run build` | Create a production build in the `dist` folder |
26 | | `npm run dev-nolog` | Launch a development web server without sending anonymous data (see "About log.js" below) |
27 | | `npm run build-nolog` | Create a production build in the `dist` folder without sending anonymous data (see "About log.js" below) |
28 |
29 | ## Writing Code
30 |
31 | After cloning the repo, run `npm install` from your project directory. Then, you can start the local development server by running `npm run dev`.
32 |
33 | The local development server runs on `http://localhost:8080` by default. Please see the Next.js documentation if you wish to change this, or add SSL support.
34 |
35 | Once the server is running you can edit any of the files in the `src` folder. Next.js will automatically recompile your code and then reload the browser.
36 |
37 | ## Template Project Structure
38 |
39 | We have provided a default project structure to get you started. This is as follows:
40 |
41 | | Path | Description |
42 | |-------------------------------|-----------------------------------------------------------------------------|
43 | | `src/pages/_document.tsx` | A basic Next.js component entry point. It is used to define the `` and `` tags and other globally shared UI. |
44 | | `src` | Contains the Next.js client source code. |
45 | | `src/styles/globals.css` | Some simple global CSS rules to help with page layout. You can enable Tailwind CSS here. |
46 | | `src/page/_app.tsx` | The main Next.js component. |
47 | | `src/App.tsx` | Middleware component used to run Phaser in client mode. |
48 | | `src/PhaserGame.tsx` | The React component that initializes the Phaser Game and serves as a bridge between React and Phaser. |
49 | | `src/game/EventBus.ts` | A simple event bus to communicate between React and Phaser. |
50 | | `src/game` | Contains the game source code. |
51 | | `src/game/main.tsx` | The main **game** entry point. This contains the game configuration and starts the game. |
52 | | `src/game/scenes/` | The Phaser Scenes are in this folder. |
53 | | `public/favicon.png` | The default favicon for the project. |
54 | | `public/assets` | Contains the static assets used by the game. |
55 |
56 |
57 | ## React Bridge
58 |
59 | The `PhaserGame.tsx` component is the bridge between React and Phaser. It initializes the Phaser game and passes events between the two.
60 |
61 | To communicate between React and Phaser, you can use the **EventBus.js** file. This is a simple event bus that allows you to emit and listen for events from both React and Phaser.
62 |
63 | ```js
64 | // In React
65 | import { EventBus } from './EventBus';
66 |
67 | // Emit an event
68 | EventBus.emit('event-name', data);
69 |
70 | // In Phaser
71 | // Listen for an event
72 | EventBus.on('event-name', (data) => {
73 | // Do something with the data
74 | });
75 | ```
76 |
77 | In addition to this, the `PhaserGame` component exposes the Phaser game instance along with the most recently active Phaser Scene using React forwardRef.
78 |
79 | Once exposed, you can access them like any regular react reference.
80 |
81 | ## Phaser Scene Handling
82 |
83 | In Phaser, the Scene is the lifeblood of your game. It is where you sprites, game logic and all of the Phaser systems live. You can also have multiple scenes running at the same time. This template provides a way to obtain the current active scene from React.
84 |
85 | You can get the current Phaser Scene from the component event `"current-active-scene"`. In order to do this, you need to emit the event `"current-scene-ready"` from the Phaser Scene class. This event should be emitted when the scene is ready to be used. You can see this done in all of the Scenes in our template.
86 |
87 | **Important**: When you add a new Scene to your game, make sure you expose to React by emitting the `"current-scene-ready"` event via the `EventBus`, like this:
88 |
89 |
90 | ```ts
91 | class MyScene extends Phaser.Scene
92 | {
93 | constructor ()
94 | {
95 | super('MyScene');
96 | }
97 |
98 | create ()
99 | {
100 | // Your Game Objects and logic here
101 |
102 | // At the end of create method:
103 | EventBus.emit('current-scene-ready', this);
104 | }
105 | }
106 | ```
107 |
108 | You don't have to emit this event if you don't need to access the specific scene from React. Also, you don't have to emit it at the end of `create`, you can emit it at any point. For example, should your Scene be waiting for a network request or API call to complete, it could emit the event once that data is ready.
109 |
110 | ### React Component Example
111 |
112 | Here's an example of how to access Phaser data for use in a React Component:
113 |
114 | ```ts
115 | import { useRef } from 'react';
116 | import { IRefPhaserGame } from "./game/PhaserGame";
117 |
118 | // In a parent component
119 | const ReactComponent = () => {
120 |
121 | const phaserRef = useRef(); // you can access to this ref from phaserRef.current
122 |
123 | const onCurrentActiveScene = (scene: Phaser.Scene) => {
124 |
125 | // This is invoked
126 |
127 | }
128 |
129 | return (
130 | ...
131 |
132 | ...
133 | );
134 |
135 | }
136 | ```
137 |
138 | In the code above, you can get a reference to the current Phaser Game instance and the current Scene by creating a reference with `useRef()` and assign to PhaserGame component.
139 |
140 | From this state reference, the game instance is available via `phaserRef.current.game` and the most recently active Scene via `phaserRef.current.scene`.
141 |
142 | The `onCurrentActiveScene` callback will also be invoked whenever the the Phaser Scene changes, as long as you emit the event via the EventBus, as outlined above.
143 |
144 | ## Handling Assets
145 |
146 | To load your static games files such as audio files, images, videos, etc place them into the `public/assets` folder. Then you can use this path in the Loader calls within Phaser:
147 |
148 | ```js
149 | preload ()
150 | {
151 | // This is an example of loading a static image
152 | // from the public/assets folder:
153 | this.load.image('background', 'assets/bg.png');
154 | }
155 | ```
156 |
157 | When you issue the `npm run build` command, all static assets are automatically copied to the `dist/assets` folder.
158 |
159 | ## Deploying to Production
160 |
161 | After you run the `npm run build` command, your code will be built into a single bundle and saved to the `dist` folder, along with any other assets your project imported, or stored in the public assets folder.
162 |
163 | In order to deploy your game, you will need to upload *all* of the contents of the `dist` folder to a public facing web server.
164 |
165 | ## Customizing the Template
166 |
167 | ### Next.js
168 |
169 | If you want to customize your build, such as adding plugin (i.e. for loading CSS or fonts), you can modify the `next.config.mjs` file for cross-project changes, or you can modify and/or create new configuration files and target them in specific npm tasks inside of `package.json`. Please see the [Next.js documentation](https://nextjs.org/docs) for more information.
170 |
171 | ## About log.js
172 |
173 | If you inspect our node scripts you will see there is a file called `log.js`. This file makes a single silent API call to a domain called `gryzor.co`. This domain is owned by Phaser Studio Inc. The domain name is a homage to one of our favorite retro games.
174 |
175 | We send the following 3 pieces of data to this API: The name of the template being used (vue, react, etc). If the build was 'dev' or 'prod' and finally the version of Phaser being used.
176 |
177 | At no point is any personal data collected or sent. We don't know about your project files, device, browser or anything else. Feel free to inspect the `log.js` file to confirm this.
178 |
179 | Why do we do this? Because being open source means we have no visible metrics about which of our templates are being used. We work hard to maintain a large and diverse set of templates for Phaser developers and this is our small anonymous way to determine if that work is actually paying off, or not. In short, it helps us ensure we're building the tools for you.
180 |
181 | However, if you don't want to send any data, you can use these commands instead:
182 |
183 | Dev:
184 |
185 | ```bash
186 | npm run dev-nolog
187 | ```
188 |
189 | Build:
190 |
191 | ```bash
192 | npm run build-nolog
193 | ```
194 |
195 | Or, to disable the log entirely, simply delete the file `log.js` and remove the call to it in the `scripts` section of `package.json`:
196 |
197 | Before:
198 |
199 | ```json
200 | "scripts": {
201 | "dev": "node log.js dev & dev-template-script",
202 | "build": "node log.js build & build-template-script"
203 | },
204 | ```
205 |
206 | After:
207 |
208 | ```json
209 | "scripts": {
210 | "dev": "dev-template-script",
211 | "build": "build-template-script"
212 | },
213 | ```
214 |
215 | Either of these will stop `log.js` from running. If you do decide to do this, please could you at least join our Discord and tell us which template you're using! Or send us a quick email. Either will be super-helpful, thank you.
216 |
217 | ## Join the Phaser Community!
218 |
219 | We love to see what developers like you create with Phaser! It really motivates us to keep improving. So please join our community and show-off your work 😄
220 |
221 | **Visit:** The [Phaser website](https://phaser.io) and follow on [Phaser Twitter](https://twitter.com/phaser_)
222 | **Play:** Some of the amazing games [#madewithphaser](https://twitter.com/search?q=%23madewithphaser&src=typed_query&f=live)
223 | **Learn:** [API Docs](https://newdocs.phaser.io), [Support Forum](https://phaser.discourse.group/) and [StackOverflow](https://stackoverflow.com/questions/tagged/phaser-framework)
224 | **Discord:** Join us on [Discord](https://discord.gg/phaser)
225 | **Code:** 2000+ [Examples](https://labs.phaser.io)
226 | **Read:** The [Phaser World](https://phaser.io/community/newsletter) Newsletter
227 |
228 | Created by [Phaser Studio](mailto:support@phaser.io). Powered by coffee, anime, pixels and love.
229 |
230 | The Phaser logo and characters are © 2011 - 2025 Phaser Studio Inc.
231 |
232 | All rights reserved.
233 |
--------------------------------------------------------------------------------