【发布时间】:2017-06-21 20:24:18
【问题描述】:
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;
}
}
<canvas id="gc"></canvas>
在这个基本的 Pong 程序中,我使用document.addEventListener("keydown", keyDown); 来控制球拍的运动。但是,该函数没有以一致的速率被调用(运动不是流畅的)。第一次按下被记录,然后稍微停顿,然后它流畅地移动。 (类似于如果您按住一个字母键,它会输入一个字母。如果您继续按住它,它会继续输入字母,但不会在稍作停顿之前?不确定我是否清楚......)
有没有办法使用“keydown”事件监听器进行一致的输入/函数调用?
【问题讨论】:
-
听起来你想"debounce"你的事件处理,以便它变得更加一致。
-
不一定。在第一个函数调用之后输入是流动的,只是第一个和第二个之间的差距是奇数。
-
这取决于您的操作系统的键重复率。您使用的是什么操作系统?
-
在
keydown上设置标志,在keyup上取消设置。检查每个requestAnimationFrame回调中的标志状态(或者您运行游戏循环)。
标签: javascript html canvas