/
ion-phaser.tsx
88 lines (75 loc) 路 1.84 KB
/
ion-phaser.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import { Component, Prop, Watch, Element, Method } from '@stencil/core'
import { GameInstance } from '../models/game'
declare const Phaser: any
@Component({
tag: 'ion-phaser',
styleUrl: 'ion-phaser.css',
shadow: false
})
export class IonPhaser {
@Element() el!: HTMLIonPhaserElement
/**
* Set the configuration of the game
*/
@Prop({
mutable: true,
reflect: true
}) game?: GameInstance
@Watch('game')
onGameChange(game: GameInstance) {
if (this.initialize && !this.hasInitialized()) {
this.initializeGame(game)
}
}
/**
* Initialize the phaser game manually
*/
@Prop() initialize?: boolean = true
@Watch('initialize')
onInitialize(newInitialize: boolean, oldInitialize: boolean) {
if (newInitialize && !oldInitialize) {
this.initializeGame()
}
}
/**
* Get the Phaser game instance
*/
@Method()
async getInstance(): Promise<GameInstance['instance']> {
const { instance } = this.game || {}
return Promise.resolve(instance)
}
/**
* Destroy the Phaser game instance
*/
@Method()
async destroy(): Promise<void> {
if (this.hasInitialized()) {
this.game.instance.destroy(true)
this.game.instance = null
}
}
connectedCallback() {
if (!this.hasInitialized() && this.initialize) {
this.initializeGame()
}
}
disconnectedCallback() {
this.destroy()
}
private hasInitialized(): boolean {
return (
this.game &&
this.game.instance !== undefined &&
this.game.instance !== null
)
}
private initializeGame = (game = this.game) => {
if(game === null || game === undefined) return
if(game.instance !== undefined && game.instance !== null) {
throw new Error("A Phaser game already exist")
}
game.parent = game.parent || this.el
game.instance = new Phaser.Game(game)
}
}