【问题标题】:How to set keyboard key pressed event only once after pressed but not continously如何在按下后仅设置一次键盘按键事件而不是连续设置
【发布时间】:2018-06-23 03:26:35
【问题描述】:

我正在使用下面的代码向上移动播放器,但问题是只要按住按钮,播放器就会继续移动。我怎样才能改变这种行为,以便无论玩家按下按钮多少次都只移动一次?

if (cursor.up.isDown){
     player.body.velocity.y = -200;
     player.animations.stop('move');
}

【问题讨论】:

    标签: phaser-framework


    【解决方案1】:

    充当触发器开关的 bool 应该可以完成这项工作:

    var flipFlop;
    
    function update() {
        if (cursor.up.isDown){
            if (!flipFlop) {
                player.body.velocity.y = -200;
                player.animations.stop('move');
                flipFlop = true;
            }
        }
    
        if (cursor.up.isUp) {
            flipFlop = false;
        }
    }
    

    注意,flipFlop 变量是在更新循环之外声明的,否则每帧都会重新创建。

    【讨论】:

    • thanx kamen,我已经实现了一个类似且简单得多的触发器,现在一切正常!!
    【解决方案2】:

    Kamen Minkov 的回答确实有效,但如果您的想法是跳跃,则 bool 将不起作用,一旦您意识到按钮,您就可以再次按下它并继续往上走,甚至不触及任何地面。

    但是你可以使用这个函数来验证身体是否正在触地

    function touchingDown(someone) {
    var yAxis = p2.vec2.fromValues(0, 1);
    var result = false;
    for (var i = 0; i < game.physics.p2.world.narrowphase.contactEquations.length; i++) {
        var c = game.physics.p2.world.narrowphase.contactEquations[i];
        if (c.bodyA === someone.data || c.bodyB === someone.data)        {
            var d = p2.vec2.dot(c.normalA, yAxis); // Normal dot Y-axis
            if (c.bodyA === someone.data) d *= -1;
            if (d > 0.5) result = true;
        }
    } return result;
    }
    

    并调用发送正文

    if ( (cursor.up.isDown) && (touchingDown(player.body)) ){
            player.body.velocity.y = -200;
            player.animations.stop('move');
    }
    

    OBS:适用于 P2 Physics 的功能,但对于街机游戏,身体已经有一个字段表明它是否正在着陆。

    【讨论】:

    • 我在碰撞事件回调中使用了一个简单的触发器,现在一切正常,谢谢!!
    • 碰撞事件中的触发器,很聪明。
    【解决方案3】:

    我知道这是一篇旧帖子,但我也被困在这里,并使用您的示例提出了这个不错且简单的解决方案

    this.speed = 100
    this.player.setVelocity(0,0)
    if (this.cursors.left.isDown){
      this.player.setVelocityX(-this.speed)
    }else if(this.cursors.right.isDown){
      this.player.setVelocityX(this.speed)
    }else{
      this.player.setVelocityX(0)
    }if(this.cursors.up.isDown){
      this.player.setVelocityY(-this.speed)
    }else if (this.cursors.down.isDown){
      this.player.setVelocityY(+this.speed)
    }else{
      this.player.setVelocityY(0)
    }
    

    首先,我们将玩家速度设置为 0 , 0(x 和 y)。 我们检查 x 轴上的任何变化,否则将其重置为 0。 检查 y 轴是否有更改,否则也将其重置为 0。

    我发现这可以让角色以更流畅的动作移动。并且还允许将左和上等压在一起。 如果您需要角色移动更多方形,则将速度更改为 .x 或 .y

    【讨论】:

      猜你喜欢
      • 2012-05-10
      • 2020-07-12
      • 2013-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多