如何将游戏角色保留在画布中?

时间:2018-08-30 13:40:55

标签: javascript canvas web-applications keyboard

我正在开发类似“蛙人”的游戏,并且具有以下代码来围绕画布元素移动角色。该代码有效,但是角色能够“退出/离开”画布。我曾尝试将handleInput()放在if语句(update(dt)中嵌套的if player.x is > don't do this....(更新检查更新)中,但是出现语法错误。 switch中的三元语句有效-但是,这就是他们在我遵循的教程中所做的事情,并且我正努力尝试不只是“复制”该教程。任何建议深表感谢!

window.allowedKeys = {
    37: 'left',
    38: 'up',
    39: 'right',
    40: 'down'
};

const allowedKeys = window.allowedKeys;

 update(dt){

    }

    handleInput(input){

        switch(input) {
            case 'left':
             allowedKeys['left'] = this.x -= 1;
                break;
            case 'up':
            allowedKeys['up'] = this.y -= 1;
                break;
            case 'right':
            allowedKeys['right'] = this.x += 1;
                break;
            case 'down':
            allowedKeys['down'] = this.y += 1;
                break;
            default:
                break;
        }
    }
document.addEventListener('keyup', function(e) {

    player.handleInput(allowedKeys[e.keyCode]);

});

2 个答案:

答案 0 :(得分:0)

将此功能添加到update()可以解决此问题:),并具有向左/向右滚动屏幕的乐趣!

update(dt){
       if(player.x > 5){
           player.x = 0;
       }
       if(player.x < 0){
        player.x = 5;
    }
        if(player.y > 4.5){
            player.y -= 1;
        }
    }

答案 1 :(得分:0)

我认为您想验证用户的密钥是什么,请按此处,这是一个示例,我使用原型,但我认为您使用的是es6类。您无需声明全局var allowedKeys也不更新它。希望对您有帮助

// movements with javascript
const allowedKeys = {
    37: 'left',
    38: 'up',
    39: 'right',
    40: 'down'
};

function Player(target)  {
  this.x = 0
  this.y = 0
  this.target = target
}

Player.prototype.handleInput = function(input){
        switch(input) {
            case 'left':
               this.x -= 1;
                break;
            case 'up':
              this.y -= 1;
                break;
            case 'right':
              this.x += 1;
                break;
            case 'down':
              this.y += 1;
                break;
            default:
                break;
        }
    }


Player.prototype.update = function (dt){

}

const player = new Player("player1")

document.addEventListener('keyup', function(e) {
    player.handleInput(allowedKeys[e.keyCode]);
    const element = document.getElementById(player.target)
    element.innerHTML = "x:" + player.x + "  y:" + player.y
});
<div id="player1"> Press an Arrow </div>