我正在使用Phaser 3中的用户输入制作角色动画(使用纹理图谱),我遇到了一个问题,当我释放相应的箭头按钮时,动画没有停止.我试过一些策略,有些只是部分奏效.下面的代码是我使用的,它在所有方面都按照预期工作,除了释放相应的箭头键后动画没有停止.也许我需要逻辑与停止动画一旦键被解除?有什么建议吗?谢谢!

一百零二 Sprite Sheet animation with arrow keys.

update() {      

    this.hero.setVelocity(0,0);

    if (this.cursors.up.isDown) {
        this.hero.anims.play('walkUp', true); 
        this.hero.setVelocityY(-200);                     
    } 
    
    else if (this.cursors.down.isDown) {
        this.hero.anims.play('walkDown', true) 
        this.hero.setVelocityY(200);
    }         

    if (this.cursors.left.isDown) {    
        this.hero.anims.play('walkLeft', true)
        this.hero.setVelocityX(-200);
    } 

    else if (this.cursors.right.isDown) {
        this.hero.anims.play('walkRight', true)
        this.hero.setVelocityX(200);
    }                
}

推荐答案

有很多方法可以解决这个问题.你的解决方案当然是有效的,但这里有两个替代方案,这将使你的代码更短更容易阅读.

Update:2.

Alternative 1

由于移动到leftright覆盖了updown移动,你可以简单地重新排序if/else个块,并将它们全部链接为ob big if/else块,并停止动画在最后的else.(104, your 103 only override the animation)

update() {      

    this.hero.setVelocity(0,0);

    if (this.cursors.left.isDown) {    
        this.hero.anims.play('walkLeft', true)
        this.hero.setVelocityX(-200);
    } 
    else if (this.cursors.right.isDown) {
        this.hero.anims.play('walkRight', true)
        this.hero.setVelocityX(200);
    } 
    else if (this.cursors.up.isDown) {
        this.hero.anims.play('walkUp', true); 
        this.hero.setVelocityY(-200);                     
    } 
    else if (this.cursors.down.isDown) {
        this.hero.anims.play('walkDown', true) 
        this.hero.setVelocityY(200);
    }
    else {
        this.hero.anims.stop();
    }   
}

Alternative 2

只需在update函数的结尾处判断一下,velocity长度是否等于或多或少等于零.(由于物体通常不会真正停止(由于重力,glide和一些物理圆的东西)< 2应该保存/可以使用)

update() {      

    // ...  your initial code 
    if (this.hero.body.velocity.length() < 2) {
        this.hero.anims.stop();
    }   
     
}

在个人喜欢第一个替代,但取决于你的使用情况,如果你需要处理up/downleft/right独立,后者应该也是好的.

改进了Alternative 2,但稍微长一些,你可以判断关键事件而不是velocity长度,它会"更干净".

if (!this.cursors.up.isDown &&
    !this.cursors.down.isDown &&
    !this.cursors.left.isDown &&
    !this.cursors.right.isDown ){
        this.hero.anims.stop();
}

Javascript相关问答推荐

如何使用Echart 5.5.0创建箱形图

如何避免移动设备中出现虚假调整大小事件?

django无法解析余数:[0] from carray[0]'

如何用显示网格平滑地将元素从一个地方移动到另一个地方?

点击按钮一次有文本出现和褪色,而不是点击两次?(html,CSS,JavaScript)

为什么useState触发具有相同值的呈现

在HTML语言中调用外部JavaScript文件中的函数

如何发送从REST Api收到的PNG数据响应

第三方包不需要NODE_MODULES文件夹就可以工作吗?

JavaScript是否有多个`unfined`?

将Node.js包发布到GitHub包-错误ENEEDAUTH

面对代码中的错误作为前端与后端的集成

为什么云存储中的文件不能公开使用?

每次重新呈现时调用useState initialValue函数

如何用javascript更改元素的宽度和高度?

我为什么要使用回调而不是等待?

TypeORM QueryBuilder限制联接到一条记录

Django模板中未加载JavaScript函数

正在发出错误的URL请求

使用JAVASCRIPT-使用If和Else If多次判断条件-使用JAVASRIPT对象及其属性