我正在使用GameObjectFactory
注册myPlayer
import Phaser from 'phaser'
import Player from './Player'
import { Direction } from '@/types/phaser';
export default class MyPlayer extends Player {
constructor(
scene: Phaser.Scene,
x: number,
y: number,
defaultDirection: Direction
) {
super(scene, x, y, defaultDirection)
scene.add.existing(this)
}
}
declare global {
namespace Phaser.GameObjects {
interface GameObjectFactory {
myPlayer(x: number, y: number, defaultDirection: Direction): MyPlayer
}
}
}
Phaser.GameObjects.GameObjectFactory.register(
'myPlayer',
function (
this: Phaser.GameObjects.GameObjectFactory,
x: number,
y: number,
defaultDirection: Direction
) {
const sprite = new MyPlayer(this.scene, x, y, defaultDirection)
this.displayList.add(sprite)
this.updateList.add(sprite)
return sprite
}
)
我尝试在场景中使用this.add.myPlayer
import Phaser from 'phaser'
import MyPlayer from '@/players/MyPlayer'
import { CustomCursorKeys } from '@/types/phaser'
import { Direction } from '@/types/phaser'
export default class BaseScene extends Phaser.Scene {
public cursors: CustomCursorKeys | null = null
public myPlayer: MyPlayer | null = null
constructor(key: string) {
super(key)
}
create(param: {
map: Phaser.Tilemaps.Tilemap,
x: number,
y: number,
direction: Direction
}) {
console.log('this.add.myPlayer', this.add.myPlayer)
this.myPlayer = this.add.myPlayer(705, 500, 'up')
}
}
但是this.add.myPlayer
控制台记录为undefined
。我做错了什么?
1条答案
按热度按时间c2e8gylq1#
最好的办法是尽量让代码接近this offical example。
你必须创建你自己的 * 自定义对象/精灵 *,创建一个 * 自定义插件 * 和 * 注册 * 插件在 * 游戏配置 *。
这里是一个可能的例子,它可能是这样的:
播放器文件:
场景文件:
游戏创建: