【发布时间】:2020-01-31 20:49:26
【问题描述】:
我正在尝试创建一个基本的平台游戏,并且正在研究重力部分。我正在使用一些 if myGameArea.keys 语句来允许玩家前后移动角色。当按下向上键时,我正在使用加速功能来停止重力,但是当抬起键时我无法让它重新开始。我知道如何实现 onkeyup 函数 (onkeyup = function();) 但我不知道如何将它添加到我的代码中。
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
border:1px solid #d3d3d3;
background-color: #f1f1f1;
}
</style>
</head>
<body onload="startGame()">
<script>
var myGamePiece;
function startGame() {
myGameArea.start();
myGamePiece = new component(30, 30, "red", 10, 240);
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 480;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas,
document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
window.addEventListener('keydown', function (e) {
myGameArea.keys = (myGameArea.keys || []);
myGameArea.keys[e.keyCode] = (e.type == "keydown");
})
window.addEventListener('keyup', function (e) {
myGameArea.keys[e.keyCode] = (e.type == "keyup");
})
},
clear : function(){
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function component(width, height, color, x, y, type) {
this.type = type;
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.speedX = 0;
this.speedY = 0;
this.gravity = 0.05;
this.gravitySpeed = 0;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.newPos = function() {
this.gravitySpeed += this.gravity;
this.x += this.speedX;
this.y += this.speedY + this.gravitySpeed;
this.hitBottom();
}
this.hitBottom = function() {
var rockbottom = myGameArea.canvas.height - this.height;
if (this.y > rockbottom) {
this.y = rockbottom;
}
}
}
function updateGameArea() {
myGameArea.clear();
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
myGamePiece.gravity = 0.1;
if (myGameArea.keys && myGameArea.keys[37]) {myGamePiece.speedX = -2;
}
if (myGameArea.keys && myGameArea.keys[39]) {myGamePiece.speedX = 2;
}
if (myGameArea.keys && myGameArea.keys[38]) {accelerate(-0.2)}
myGamePiece.newPos();
myGamePiece.update();
}
function accelerate(n) {
myGamePiece.gravity = n;
}
</script>
</body>
</html>
这只是代码的一小部分。如果有人想要全额,请在下面评论告诉我。感谢您的帮助!
【问题讨论】:
-
你有一个
keydown事件来检测按键吗?似乎这也是您想要放置keyup事件注册的地方。 -
谢谢!我没有意识到,但这是代码的单独部分。我会编辑添加这个,我会尝试在那里改变一些东西。
-
我也有一个keyup部分。我会看看如何使用它。
标签: javascript html game-physics keycode onkeyup