如何在 JavaScript 突破游戏中将球保持在墙内?

How to keep the ball within the wall boundaries in JavaScript breakout game?

我正在创建一个 Javascript 突破游戏,但在将球保持在墙边界内时遇到了问题。

在 运行 程序中,球拍与在 window 中间创建的静态球配合得很好。直到我设置代码使球保持在墙边界内(顶部、左侧和右侧),此时,错误发生并且整个程序停止工作。

我已经尝试了几种 if/else 变体来修复它,但无法弄清楚为什么代码不起作用。 JavaScript代码如下:

function createPaddle(gw) {
  let x0 = (gw.getWidth() - PADDLE_WIDTH) / 2;
  let y0 = PADDLE_Y;
  let paddle = GRect(x0, y0, PADDLE_WIDTH, PADDLE_HEIGHT);
  paddle.setFilled(true);
  gw.add(paddle);

  let mouseMoveAction = function(e) {
    let x = e.getX() - (PADDLE_WIDTH / 2);
    let y = PADDLE_Y;
    if (x > 0 && x <= gw.getWidth() - PADDLE_WIDTH) {
      paddle.setLocation(x, y);
    }
  };
  gw.addEventListener("mousemove", mouseMoveAction);
}


function createBall(gw) {
  let centerX = gw.getWidth() / 2;
  let centerY = gw.getHeight() / 2;
  let x0 = centerX - (BALL_SIZE / 2);
  let y0 = centerY - (BALL_SIZE / 2);
  let ball = GOval(x0, y0, BALL_SIZE, BALL_SIZE);
  ball.setFilled(true);
  gw.add(ball);

  let clickAction = function(e) {
    let vy = INITIAL_Y_VELOCITY;
    let vx = randomReal(MIN_X_VELOCITY, MAX_X_VELOCITY);
    if (randomChance()) vx = -vx;

    let step = funtion() {
      if (ball.getX() > 0 && ball.getY() > 0 &&
          ball.getX() < gw.getWidth() - BALL_SIZE &&
          ball.getY() < gw.getHeight() - BALL_SIZE) {
        ball.move(vx, vy);
      } if (ball.getX() < 0 || ball.getX() > gw.getWidth() - BALL_SIZE) {
        vx = -vx;
        ball.move(vx, vy);
      } if (ball.getY() < 0) {
        vy = -vy;
        ball.move(vx, vy);
      } else if (ball.getY() > gw.getHeight() - BALL_SIZE) {
        clearInterval(timer);
      }
    };
    let timer = setInterval(step, TIME_STEP);
  };
  gw.addEventListener("click", clickAction);
}

非常感谢您的帮助。谢谢!

问题是错字:

let step = funtion()

改为:

let step = function()

考虑使用一些 IDE/Editor,它会在出现此类拼写错误时通知您。我使用 visual studio 代码告诉我出了点问题:


  • 在更正您的错字之前

  • 修正错字后