window.onload = function() {
canv = document.getElementById("gc");
canv.width = 500;
canv.height = 300;
ctx = canv.getContext("2d");
document.addEventListener("keydown", keyDown);
setInterval(game, 10);
}
function Paddle(x, y) {
this.x = x;
this.y = y;
this.l = 50;
this.score = 0;
}
function Ball(x, y, xv, yv) {
this.x = x;
this.y = y;
this.xv = xv;
this.yv = yv;
this.s = 5;
this.update = function() {
this.x += this.xv;
this.y += this.yv;
}
}
function drawLine(x1, y1, x2, y2) {
ctx.beginPath();
ctx.moveTo(x1, y1)
ctx.lineTo(x2, y2)
ctx.stroke();
ctx.closePath();
}
function random(min, max) {
var i = 0;
while (!i) {
i = Math.floor(Math.random() * (max - min + 1) + min);
}
return i;
}
p1 = new Paddle(10, 125);
p2 = new Paddle(490, 125);
b = new Ball(250, 150, random(-2, 2), random(-2, 2));
function game() {
b.update();
if (p1.y < 0)
p1.y = 0;
else if (p1.y + p1.l > canv.height)
p1.y = canv.height - p1.l;
if (p2.y < 0)
p2.y = 0;
else if (p2.y + p2.l > canv.height)
p2.y = canv.height - p2.l;
if (b.y < 0 || b.y > canv.height)
b.yv = -b.yv;
if (b.x < 0) {
p2.score++;
b = new Ball(30, 150, random(0, 2), random(-2, 2));
} else if (b.x > canv.width) {
p1.score++;
b = new Ball(canv.width - 30, 150, random(-2, 0), random(-2, 2));
}
if ((b.x == p1.x && b.y > p1.y && b.y + b.s < p1.y + p1.l) ||
b.x + b.s == p2.x && b.y > p2.y && b.y + b.s < p2.y + p2.l)
b.xv = -b.xv;
ctx.fillStyle = "black";
ctx.fillRect(0, 0, canv.width, canv.height);
ctx.strokeStyle = "white";
drawLine(p1.x, p1.y, p1.x, p1.y + p1.l);
drawLine(p2.x, p2.y, p2.x, p2.y + p2.l);
ctx.fillStyle = "white";
ctx.fillRect(b.x, b.y, b.s, b.s);
ctx.font = "30px sans serif";
ctx.fillText(p1.score, 200, 50);
ctx.fillText(p2.score, 300, 50);
}
function keyDown(evt) {
switch (evt.keyCode) {
case 83:
p1.y += 10;
break;
case 87:
p1.y -= 10;
break;
case 40:
p2.y += 10;
break;
case 38:
p2.y -= 10;
break;
}
}
&#13;
<canvas id="gc"></canvas>
&#13;
在这个基本的Pong程序中,我使用document.addEventListener("keydown", keyDown);
来控制桨的运动。但是,该函数不是以一致的速率调用(运动不流畅)。第一次按下是注册,然后是轻微停顿,然后它会流畅地移动。 (类似于如果你按住一个字母键,它会键入一个字母。如果你继续按住它,它会继续输入字母,但不会在稍微停顿之前?不确定我是否在这里清楚......)
有没有办法使用&#34; keydown&#34;进行一致的输入/函数调用?事件监听器?
答案 0 :(得分:1)
您可以通过在keydown
上设置变量值并在keyup
上清除变量来平滑操作系统键盘重复率的影响。例如:
let direction = null;
document.addEventListener("keydown", function (evt) {
switch (evt.keyCode) {
case 83:
direction = "down";
break;
case 87:
direction = "up";
break;
case 40:
direction = "down";
break;
case 38:
direction = "up";
break;
default:
direction = null;
}
});
document.addEventListener("keyup", function (evt) {
direction = null;
})
在游戏循环的每次迭代中检查此变量的状态。大多数HTML5游戏使用requestAnimationFrame
。