Files
test1/app/game/page.tsx

56 lines
1.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'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>
)
}