我无法弄清楚如何使用up-key使myGamePiece跳转。首先,我尝试了简单的“myGamePiece.speedY = 1”,但这不起作用。也没有尝试在函数中反转“this.gravitySpeed”。有人可以帮助我,如果可能的话解释为什么我的不工作而你的工作呢?提前致谢!我的借口如果似乎很长,我无法在不删除组件代码的情况下进一步缩短它。
对代码的解释:
function startGame:开始游戏
var myGameArea:允许乘以两个键
功能组件:生成对象及其特征
function updateGameArea:允许移动对象
<!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() {
myGamePiece = new component(30, 30, "red", 80, 75);
myGameArea.start();
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
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] = true;
})
window.addEventListener('keyup', function (e) {
myGameArea.keys[e.keyCode] = false;
})
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function component(width, height, color, x, y, type) {
this.width = width;
this.height = height;
this.x = x;
this.y = y;
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;
if (myGameArea.keys && myGameArea.keys[37]) {myGamePiece.speedX = -2; }
if (myGameArea.keys && myGameArea.keys[39]) {myGamePiece.speedX = 2; }
if (myGameArea.keys && myGameArea.keys[38]) {myGamePiece.speedY = -1; }
if (myGameArea.keys && myGameArea.keys[40]) {myGamePiece.speedY = 1; }
myGamePiece.newPos();
myGamePiece.update();
}
</script>
</body>
</html>
答案 0 :(得分:0)
问题是gravitySpeed
变量的值不断增加。
尝试在gravitySpeed
支票中将hitBottom
变量值重置为0:
if (this.y > rockbottom) {
this.y = rockbottom;
this.gravitySpeed = 0;
}
您可能还希望在调试时实时查看某些参数的值:
将这样的块添加到您的html中
<div style="position:absolute; width: 300px; bottom: 50px; right: 50px;">
<p>sppedY: <span id="speedY"></span></p>
<p>gravitySpeed: <span id="gravitySpeed"></span></p>
<p>posY: <span id="posY"></span></p>
</div>
和updateGameArea函数中的这样一个块
...
myGamePiece.newPos();
// -- debug --
speedY.innerText = myGamePiece.speedY.toFixed(2);
gravitySpeed.innerText = myGamePiece.gravitySpeed.toFixed(2);
posY.innerText = myGamePiece.y.toFixed(2);
// -----------
myGamePiece.update();