feat(app/game): 创建游戏页面,动态加载 Phaser 保证 SSR 安全
This commit is contained in:
55
app/game/page.tsx
Normal file
55
app/game/page.tsx
Normal file
@@ -0,0 +1,55 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useRef } from 'react'
|
||||
|
||||
/**
|
||||
* 游戏页面
|
||||
* Phaser 通过动态 import 加载,确保 SSR 安全(不在服务端执行)
|
||||
*/
|
||||
export default function GamePage() {
|
||||
const gameRef = useRef<{ destroy: (removeCanvas: boolean) => void } | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
let mounted = true
|
||||
|
||||
const initGame = async () => {
|
||||
// 动态导入 Phaser,避免 SSR 环境报错
|
||||
const Phaser = (await import('phaser')).default
|
||||
const { createGameConfig } = await import('@/game/config')
|
||||
const { createGameScene } = await import('@/game/GameScene')
|
||||
|
||||
if (!mounted) return
|
||||
|
||||
const GameScene = createGameScene(Phaser)
|
||||
const config = createGameConfig('game-container')
|
||||
|
||||
// 注入场景
|
||||
config.scene = [GameScene]
|
||||
|
||||
// 手动设置 scale mode(避免 SSR 时引用 Phaser.Scale 常量报错)
|
||||
if (config.scale) {
|
||||
config.scale.mode = Phaser.Scale.FIT
|
||||
config.scale.autoCenter = Phaser.Scale.CENTER_BOTH
|
||||
}
|
||||
|
||||
// type 设置
|
||||
config.type = Phaser.AUTO
|
||||
|
||||
gameRef.current = new Phaser.Game(config)
|
||||
}
|
||||
|
||||
initGame().catch(console.error)
|
||||
|
||||
return () => {
|
||||
mounted = false
|
||||
gameRef.current?.destroy(true)
|
||||
gameRef.current = null
|
||||
}
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div className="w-full h-screen overflow-hidden" style={{ backgroundColor: '#0F0F23' }}>
|
||||
<div id="game-container" className="w-full h-full" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user