[英]How to keep the ball within the wall boundaries in JavaScript breakout game?
I'm creating a Javascript breakout game but have an issue with keeping the ball within the wall boundaries.我正在创建一个 Javascript 突破游戏,但在将球保持在墙边界内时遇到了问题。
On running the program, the paddle works fine with a static ball created right in the middle of the window.在运行程序时,桨可以与在窗口中间创建的静态球一起正常工作。 Until i set the code to keep the ball within the wall boundaries (top, left, and right), at this point, error occurred and the whole program ceased to work.直到我将代码设置为将球保持在墙壁边界(顶部、左侧和右侧)内,此时,发生错误并且整个程序停止工作。
I've tried several if/else variations to mend it but can't figure out why the code is not working.我已经尝试了几个 if/else 变体来修复它,但无法弄清楚为什么代码不起作用。 JavaScript code as follows: 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);
}
Your help is much appreciated.非常感谢您的帮助。 Thanks!谢谢!
The problem is a typo:问题是一个错字:
let step = funtion()
Change it to:将其更改为:
let step = function()
Consider using some IDE/Editor which will notify you for such typos.考虑使用一些 IDE/编辑器,它会在出现此类拼写错误时通知您。 I used visual studio code which told me something was wrong:我使用了 Visual Studio 代码,它告诉我出了点问题:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.