Phaser调用this.player.anims.play触发undefined报错问题求解
问题原因分析
- 你没有使用Phaser场景提供的物理精灵工厂方法创建实例:直接new
Phaser.Physics.Matter.Sprite生成的实例,默认不会自动挂载Anims动画组件,自然就没有anims属性。Phaser的内置组件(动画、交互、纹理管理等)都是通过场景工厂方法创建对象时自动注入的,手动构造原始类需要自己额外处理组件挂载。 this.load.animation加载的是全局动画缓存数据,和单个精灵的anims属性没有关系:这个方法只是把动画配置加载到全局的动画管理器中,不会给某个特定精灵自动创建anims属性,精灵需要自身挂载了动画组件后,才能调用全局动画缓存里的资源。
修复方案
- 替换create里的精灵创建代码,用场景工厂方法生成(推荐方案)
把原来的代码:
this.player = new Phaser.Physics.Matter.Sprite(this.matter.world,0,0,'character','male_1'); this.add.existing(this.player);
替换为:
this.player = this.matter.add.sprite(0, 0, 'character', 'male_1');
这个方法会自动帮你把精灵添加到场景中,同时挂载所有需要的内置组件,包括anims动画组件。
- 同步优化update中的动画调用逻辑
你当前每帧直接调用this.player.anims.play('walking_right')会导致动画每帧都被重置,永远无法播放到后续帧,建议增加状态判断再触发播放:
update() { // 示例:仅当动画未播放/当前播放动画不是目标动画时才触发播放 if (!this.player.anims.isPlaying || this.player.anims.currentAnim.key !== 'walking_right') { this.player.anims.play('walking_right') } }
- 如果你一定要手动构造原始Matter Sprite类,可以手动挂载动画组件
this.player = new Phaser.Physics.Matter.Sprite(this.matter.world,0,0,'character','male_1'); this.add.existing(this.player); // 手动注入动画组件 this.player.anims = new Phaser.GameObjects.Components.Animation(this.player);
内容的提问来源于stack exchange,提问作者Darrell Ng
相关产品推荐
相关产品推荐

