首页 > 解决方案 > 如何将我的游戏角色保留在画布中?

问题描述

我正在开发一个“类似青蛙的”游戏,并使用以下代码在画布元素周围移动我的角色。代码有效,但是角色能够“走出/离开”画布。我尝试将嵌套在 if 语句 ( )handleInput()中的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]);

});

标签: javascriptcanvasweb-applicationskeyboard

解决方案


我认为您想验证用户的密钥是什么,按这里是一个示例,我使用原型,但我相信您使用的是 es6 类。您不需要声明全局变量 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>


推荐阅读