【问题标题】:Pong game in canvas: unable to move players paddle画布上的乒乓球游戏:无法移动玩家划桨
【发布时间】: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


【解决方案1】:

您的代码中有一些错误。

  1. 您没有检查正在按下的键。
  2. 你没有在任何地方打电话给movePlayerPaddle

我不会给你写代码,只是给你方法:

  1. 在您的 drawPath 中,您在固定坐标中绘制焊盘。您必须检查是否按下了移动键并对坐标进行加/减以移动它。
  2. 更改您的事件侦听器以检查正在按下哪个键来决定设置向左或向右移动标志。
  3. 如果移动速度过快,您可以以小数步长递增坐标,例如 0.5 以减慢 50% 的移动速度。

【讨论】:

  • 感谢@Elias 的指点,我会试试看的!
猜你喜欢
  • 1970-01-01
  • 2020-08-09
  • 1970-01-01
  • 2022-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-01
相关资源
最近更新 更多