51 lines
1.5 KiB
TypeScript
51 lines
1.5 KiB
TypeScript
|
|
import Phaser from "phaser";
|
|||
|
|
import {createContext, h} from "preact";
|
|||
|
|
import {Signal, useSignalEffect, signal, useSignal} from "@preact/signals";
|
|||
|
|
import {useContext} from "preact/hooks";
|
|||
|
|
|
|||
|
|
export const phaserContext = createContext<Signal<Phaser.Game | undefined>>(signal());
|
|||
|
|
|
|||
|
|
export const defaultPhaserConfig: Phaser.Types.Core.GameConfig = {
|
|||
|
|
type: Phaser.AUTO,
|
|||
|
|
width: 560,
|
|||
|
|
height: 560,
|
|||
|
|
parent: 'phaser-container',
|
|||
|
|
backgroundColor: '#f9fafb',
|
|||
|
|
scene: [],
|
|||
|
|
};
|
|||
|
|
|
|||
|
|
export function PhaserGame(props: { config?: Partial<Phaser.Types.Core.GameConfig>, children?: any}){
|
|||
|
|
|
|||
|
|
const gameSignal = useSignal<Phaser.Game>();
|
|||
|
|
|
|||
|
|
useSignalEffect(() => {
|
|||
|
|
const phaserGame = new Phaser.Game(props.config || defaultPhaserConfig);
|
|||
|
|
gameSignal.value = phaserGame;
|
|||
|
|
|
|||
|
|
return () => {
|
|||
|
|
gameSignal.value = undefined;
|
|||
|
|
phaserGame.destroy(true);
|
|||
|
|
}
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
return <div id="phaser-container" className="w-full h-full" >
|
|||
|
|
<phaserContext.Provider value={gameSignal}>
|
|||
|
|
{props.children}
|
|||
|
|
</phaserContext.Provider>
|
|||
|
|
</div>
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
export function PhaserScene(props: { sceneKey: string, scene: Phaser.Scene, autoStart: boolean, data?: object}){
|
|||
|
|
const context = useContext(phaserContext);
|
|||
|
|
useSignalEffect(() => {
|
|||
|
|
const game = context.value;
|
|||
|
|
if(!game) return;
|
|||
|
|
|
|||
|
|
game.scene.add(props.sceneKey, props.scene, props.autoStart, props.data);
|
|||
|
|
return () => {
|
|||
|
|
game.scene.remove(props.sceneKey);
|
|||
|
|
}
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
return null;
|
|||
|
|
}
|