我正在尝试制作2人制乒乓球游戏,由于某种原因,桨不会同时移动。我为每个拨片设置了两个不同的功能,但仍然无法正常工作。 (代码中移动桨叶的部分位于脚本的底部)
//make canvas and set it up
var canvas = document.createElement('canvas');
document.body.appendChild(canvas);
var ctx = canvas.getContext('2d');
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
canvas.style.position = 'absolute';
canvas.style.left = '0px';
canvas.style.top = '0px';
canvas.style.backgroundColor = '#D0C6C6';
var cH = canvas.height;
var cW = canvas.width;
//draw paddles
//variables
var paddleLength = 120;
var redPaddleY = window.innerHeight / 2;
var bluePaddleY = window.innerHeight / 2;
var paddleWidth = 20;
//drawing starts
function drawPaddles() {
//RED PADDLE
var redPaddle = function(color) {
ctx.fillStyle = color;
ctx.fillRect(cH / 12, redPaddleY - paddleLength / 2, paddleWidth, paddleLength);
ctx.fill();
};
//BLUE PADDLE
var bluePaddle = function(color) {
ctx.fillStyle = color;
ctx.fillRect(cH / 12 * 14, bluePaddleY - paddleLength / 2, paddleWidth, paddleLength);
ctx.fill();
};
ctx.clearRect(0, 0, cW, cH);
redPaddle('red');
bluePaddle('blue');
};
var interval = setInterval(drawPaddles, 25);
//move paddles
document.addEventListener('keydown', movePaddle, true);
document.addEventListener('keydown', moveOPaddle, true);
function movePaddle(event) {
var k = event.key;
if (k == 'ArrowDown') {
bluePaddleY += 5;
} else if (k == 'ArrowUp') {
bluePaddleY -= 5;
}
}
function moveOPaddle(event) {
var k = event.key;
if (k == 's') {
redPaddleY += 5;
} else if (k == 'w') {
redPaddleY -= 5;
}
}