我一直对制作乒乓球游戏感到沮丧。我有两个球拍,我可以根据需要分别自由移动,但我错过了一些东西,它们不能像我想的那样同时移动,这是一个多人游戏,两个对手同时按下不同的键盘键,但我的代码中缺少了一些东西!
function leftPaddleMoveUp() {
leftTopLenght = leftPaddle.getBoundingClientRect().top;
if (Math.floor(leftTopLenght) === 100) {
return NaN;
} else {
leftPaddle.style.top = leftPaddleTopUp + leftPaddleTopDown + "px";
leftPaddleTopUp -= 20; // Speed
}
}
function leftPaddleMoveDown() {
leftTopLenght = leftPaddle.getBoundingClientRect().top;
if (Math.floor(leftTopLenght) === 660) {
return NaN;
} else {
leftPaddle.style.top = leftPaddleTopUp + leftPaddleTopDown + "px";
leftPaddleTopDown += 20; // Speed
}
}
function rightPaddleMoveUp() {
rightTopLenght = rightPaddle.getBoundingClientRect().top;
if (Math.floor(rightTopLenght) === 100) {
return NaN;
} else {
rightPaddle.style.top = rightPaddleTopUp + rightPaddleTopDown + "px";
rightPaddleTopUp -= 20; // Speed
}
}
function rightPaddleMoveDown() {
rightTopLenght = rightPaddle.getBoundingClientRect().top;
if (Math.floor(rightTopLenght) === 660) {
return NaN;
} else {
rightPaddle.style.top = rightPaddleTopUp + rightPaddleTopDown + "px";
rightPaddleTopDown += 20; // Speed
}
}
document.addEventListener("keypress", (event) => {
// PlayerOne&LeftSide
if (event.keyCode === 83 /*azerty & qwerty*/) {
leftPaddleMoveUp();
} else if (
event.keyCode === 87 /*azerty*/ ||
event.keyCode === 90 /*qwerty*/
) {
leftPaddleMoveDown();
}
// PlayerTwo&RightSide
else if (event.keyCode === 38 /*UpperArrow*/) {
rightPaddleMoveUp();
} else if (event.keyCode === 40 /*LowerArrow*/) {
rightPaddleMoveDown();
}
});
有什么方法或功能可以完成这项任务吗?
您应该使用keydown
和keyup
事件,并将当前按下的键存储在数组中。
const currentKeysDown = []
document.addEventListener("keydown", (event) => {
if (!currentKeysDown.includes(event.keyCode)) {
currentKeysDown.push(event.keyCode)
}
console.log(currentKeysDown)
movePaddles()
})
document.addEventListener("keyup", (event) => {
currentKeysDown.splice(currentKeysDown.indexOf(event.keyCode), 1)
console.log(currentKeysDown)
movePaddles()
})
function movePaddles() {
// PlayerOne&LeftSide
if (currentKeysDown.includes(83) /*azerty & qwerty*/ ) {
leftPaddleMoveUp();
} else if (
currentKeysDown.includes(87) /*azerty*/ ||
currentKeysDown.includes(90) /*qwerty*/
) {
leftPaddleMoveDown();
}
// PlayerTwo&RightSide
if (currentKeysDown.includes(38) /*UpperArrow*/ ) {
rightPaddleMoveUp();
} else if (currentKeysDown.includes(40) /*LowerArrow*/ ) {
rightPaddleMoveDown();
}
}
function leftPaddleMoveUp() {
console.log('Player1 moves UP')
}
function leftPaddleMoveDown() {
console.log('Player1 moves DOWN')
}
function rightPaddleMoveUp() {
console.log('Player2 moves UP')
}
function rightPaddleMoveDown() {
console.log('Player2 moves DOWN')
}