javascript - 如何将我的游戏角色保留在画布中?
问题描述
我正在开发一个“类似青蛙的”游戏,并使用以下代码在画布元素周围移动我的角色。代码有效,但是角色能够“走出/离开”画布。我尝试将嵌套在 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]);
});
解决方案
我认为您想验证用户的密钥是什么,按这里是一个示例,我使用原型,但我相信您使用的是 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>
推荐阅读
- html - 如何使无序列表居中
- python - 发生异常:OSError 无法加载共享对象文件:llvmlite.dll
- apache-kafka - apache kafka vs redis 作为生产中的消息代理
- maven - talend 7.3.1 如何将 jdbc 或 sqlserver 支持添加到路由?
- mysql - 数据库连接适用于 Kubernetes 集群,但使用 Skaffold 开发失败
- r - ggplot, geom_line() 用于数据集中字符串(分类)变量的每个值的平均出现次数
- python - Django rest框架:嵌套序列化程序为空时排除结果
- express-validator - 自定义验证器 - 何时使用 Promise.reject() 与 throw new Error()?
- video - 与 ffplay 和 VLC 相比,ffmpeg 性能不佳
- ios - 天蓝色 devOps 管道 xcode