【发布时间】:2021-09-27 02:43:46
【问题描述】:
我为投影在画布上创建了一个 pong 克隆,并创建了球拍反弹球。我已经设法将箭头键链接到事件侦听器,但我无法沿 x 轴移动桨。关于如何实现这一点的任何建议?
codepen 链接:https://codepen.io/blacksunmachine/pen/WNjOJLW
const canvas = document.querySelector('canvas')
const context = canvas.getContext('2d')
let paddleX = (canvas.width - (drawPlayerPaddle.xCoordinate))
context.fillStyle = 'green'
function drawPlayerPaddle(xCoordinate, yCoordinate, width, height) {
context.fillRect(xCoordinate, yCoordinate, width, height)
}
drawPlayerPaddle(10, 10, 100, 10)
function drawComputerPaddle (xCoordinate, yCoordinate, width, height) {
context.fillRect(xCoordinate, yCoordinate, width, height)
}
drawComputerPaddle(280, 290, 100, 10)
let x = canvas.width/152;
let y = canvas.height-280;
let dx = 2;
let dy = 2;
function drawBall () {
context.fillRect(x, y, 20, 20)
}
setInterval(drawPath, 10)
function reset() {
context.clearRect(0, 0, 400, 300)
}
function drawPath() {
reset()
drawBall()
x += dx;
y += dy;
drawPlayerPaddle(10, 10, 100, 10)
drawComputerPaddle(280, 290, 100, 10)
if(y + dy < 0 || y + dy > canvas.height) {
dy = -dy
}
if(x + dx > canvas.width || x + dx < 0) {
dx = -dx;
}
}
let ArrowRightPressed = false
let ArrowLeftPressed = false
document.addEventListener('keydown', handleKeyDown)
function handleKeyDown (event) {
// right arrow
if (event.key) {
ArrowRightPressed = true
console.log('Key down',event.key)
// left arrow
} else if (event.key){
ArrowLeftPressed = true
console.log('Key down',event.key)
}
}
document.addEventListener('keyup', handleKeyUp)
function handleKeyUp (event) {
// right arrow
if (event.key) {
ArrowRightPressed = false
console.log('Key up', event.key)
// left arrow
} else if (event.key){
ArrowLeftPressed = false
console.log('Key up', event.key)
}
}
function movePlayerPaddle() {
if(ArrowRightPressed) {
paddleX += 7
}
}
我已将 paddleX 设置为玩家桨的位置:
let paddleX = (canvas.width - (drawPlayerPaddle.xCoordinate))
和移动桨我已经设置了功能:
function movePlayerPaddle() {
if(ArrowRightPressed) {
paddleX += 7
}
}
但我无法移动桨。
我认为问题在于我没有很好地定义桨的 x 坐标,因此按钮没有链接到桨,所以不要移动它。
建议将不胜感激!
【问题讨论】:
-
第一个错误:在您的事件侦听器中,您没有检查按下/释放哪个键。因此,您的代码始终会设置/取消设置
ArrowRightPressed,而与按下哪个键无关 -
另外,你在哪里打电话
movePlayerPaddle()?
标签: javascript html5-canvas pong