Phaser 3 - currentAnim 未定义

Phaser 3 - currentAnim is undefined

我正在尝试在完成后将我的动画重置回第 0 帧。为此,我使用以下代码:

gameState.idle.play('wag', true).on('animationcomplete', () => {gameState.idle.pause(gameState.idle.currentAnim.frames[0])});

然而,当我尝试这个时,我得到了错误

Uncaught TypeError: gameState.idle.frames is undefined

我该如何解决这个问题?

如果你只是想知道,如何获取当前动画的第一帧,你可以(如果贴出的代码是正确的,并且我解释正确的话)

gameState.idle.play('wag', true).on('animationcomplete', (currentAnim) => {
    gameState.idle.pause(currentAnim.frames[0])
});

这应该有效。这里的文档 link 解释了事件的参数 ANIMATION_COMPLETE(https://photonstorm.github.io/phaser3-docs/Phaser.Animations.Events.html#event:ANIMATION_COMPLETE)

如果您不想使用传递给事件的参数,您可以使用此代码:

gameState.idle.play('wag', true).on('animationcomplete', () => {
    gameState.idle.pause(gameState.idle.anims.currentAnim.frames[0])
});

它也可以,但不太容易阅读。

under the asumption that gameState.idle is a Phaser.GameObjects.Sprite

更新(使用评论中的 jsfiddle 代码):

pause函数不是Sprite对象的函数,它是SpritePhaser.Animations.AnimationState属性的函数:

const gameState = {
    gameWidth: 400,
    gameHeight: 200,
    menu: {},
    textStyle: { 
        fontFamily: "'Comic Sans MS'", fill: "#fff", 
        align: "center",
        boundsAlignH: "left", 
        boundsAlignV: "top", 
        wordWrap: true, wordWrapWidth: 300 }
};

function preload()
{
    //this.load.baseURL = 'assets/';
    //this.load.atlas('idle', 'idle.png', 'idle.json');
  // added Image from an official phaser example, for a working example
    this.load.spritesheet('idle', 'https://labs.phaser.io/assets/animations/brawler48x48.png', { frameWidth: 48, frameHeight: 48 });
        
}

function create()
{
    
    this.anims.create({
        key: "wag",
        frameRate: 8,
        frames: this.anims.generateFrameNumbers("idle", {
            start: 0, 
            end: 5}),
        repeat: 0,
    });
    gameState.idle = this.add.sprite(200, 100, "idle");
    gameState.idle.setInteractive({cursor: 'url("assets/pet.cur"), pointer'});
}

function update()
{
    let test = Math.floor(Math.random() * (50) + 1);
    if (test == 50)
        gameState.idle.play('wag', true).on('animationcomplete', (currentAnim, frame, gameObject) =>{
    gameObject.anims.pause(currentAnim.frames[0]);
   });
}

var config = {
    backgroundColor: "0xf0f0f0",
    scale: {
        width: gameState.gameWidth,
        height: gameState.gameHeight,
        autoCenter: Phaser.Scale.CENTER_BOTH
    },
    scene: {
        preload, create, update
    }
};
var game = new Phaser.Game(config);
<script src="https://cdn.jsdelivr.net/npm/phaser@3.55.2/dist/phaser.js"></script>