I'm creating a Javascript breakout game but have an issue with keeping the ball within the wall boundaries.
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. JavaScript code as follows:
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. I used visual studio code which told me something was wrong: