Phaser 3中调用update()导致动画反复重启无法正常播放
Phaser 3 Sprite动画持续重启仅显示第一帧的解决方法
问题重现
使用Phaser 3纯JavaScript开发,主场景的update方法中调用Player实例的update,导致动画始终停在第一帧——因为每帧都会重启动画。相关代码如下:
MainGame.js
export default class MainGame extends Phaser.Scene { create () { this.player = new Player({ scene: this, x : 100, y : 100 }); } update () { this.player.update(); } }
Player.js
export default class Player extends Phaser.GameObjects.Sprite { constructor(config) { super(config.scene, config.x, config.y, 'player'); this.scene = config.scene; this.scene.add.existing(this); } update() { this.anims.play('idle_loop'); } }
已知条件:动画图集、资源加载无问题,将play()移至create方法时动画可正常循环。
问题原因
每帧调用this.anims.play('idle_loop')会强制重置动画到第一帧,导致动画永远无法进入后续帧循环。
解决方法
有两种简单的修复方式:
方式1:判断当前动画状态
在Player的update方法中,仅当未播放目标动画时才调用play:
update() { if (!this.anims.isPlaying || this.anims.currentAnim.key !== 'idle_loop') { this.anims.play('idle_loop'); } }
方式2:使用ignoreIfPlaying参数
利用play方法的第二个参数ignoreIfPlaying,设置为true时,Phaser会跳过已在播放的动画调用:
update() { // 第二个参数为true:仅在动画未播放时启动,不强制重启 this.anims.play('idle_loop', true); }
两种方式都能避免每帧重启动画,让idle_loop正常循环播放。
内容的提问来源于stack exchange,提问作者Koffee
相关产品推荐
相关产品推荐

