尽管遵循了严格的说明,但代

时间:2017-07-05 03:47:45

标签: javascript

我是Javascript编程的新手,我正在借助视频构建一个简单的乒乓球游戏。我已经按照视频中的每条指令进行操作,但它似乎没有工作。一旦超过画布宽度, ballX 应该在中间重置,但如果 X 击中右边的拍子,则应该反转。

if (ballX < 0) {
  if (ballY > paddle1Y &&
    ballY < paddle1Y + paddleHeight) {
    ballXSpeed = -ballXSpeed;
  } else {
    ballReset();
  }
  if (ballX > canvas.width) {
    if (ballY > paddle2Y &&
      ballY < paddleHeight + paddle2Y) {
      ballXSpeed = -ballXSpeed;
    } else {
      ballReset();
    }
  }
}; //ends movement();

4 个答案:

答案 0 :(得分:0)

我认为您应该将if结构更正为:

// if ballX is less than 0, expected to use is paddle1
if (ballX < 0) {
  if (ballY > paddle1Y &&
    ballY < paddle1Y + paddleHeight) {
    ballXSpeed = -ballXSpeed;
  } else {
    ballReset();
  }
}
// else if ballX is in the other side of the table, expected to use is paddle2
else if (ballX > canvas.width) {
  if (ballY > paddle2Y &&
    ballY < paddleHeight + paddle2Y) {
    ballXSpeed = -ballXSpeed;
  } else {
    ballReset();
  }
}

你的}; 错位了。

答案 1 :(得分:0)

已移动} - 看看是否有帮助

if (ballX < 0) {
  if (ballY > paddle1Y &&
    ballY < paddle1Y + paddleHeight) {
    ballXSpeed = -ballXSpeed;
  } else {
    ballReset();
  }
} // added
if (ballX > canvas.width) { // this probably should be an else if but it really doesn't matter
  if (ballY > paddle2Y &&
    ballY < paddleHeight + paddle2Y) {
    ballXSpeed = -ballXSpeed;
  } else {
    ballReset();
  }
  // a } removed from here
} //ends movement();

答案 2 :(得分:0)

如果ballX小于0,那么它永远不会大于画布宽度,这很简单地使代码部分无用。逻辑根本没有意义。

答案 3 :(得分:0)

我怀疑这可能是一些括号问题。

if (ballX < 0) {
  if ((ballY > paddle1Y) &&
    ((ballY < paddle1Y) + paddleHeight))) {
    ballXSpeed = -ballXSpeed;
  } else {
    ballReset();
  }
} // added
if (ballX > canvas.width) { // this probably should be an else if but it really doesn't matter
  if ((ballY > paddle2Y) &&
    ((ballY < paddleHeight) + paddle2Y))) {
    ballXSpeed = -ballXSpeed;
  } else {
    ballReset();
  }
  // a } removed from here
} //ends movement();