我正在创建一个Javascript突破游戏,但是在检测球与桨和砖之间的碰撞时遇到问题。
在运行程序时,桨叶在窗口壁之间的边界处工作良好。当我尝试执行代码以检测与桨和砖块的碰撞时,整个程序保持不变。
我已经尝试了几种if / else变体来修复它,但无法弄清楚为什么代码不起作用。 JavaScript代码如下:
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 checkForCollision = function(paddle, brick) {
let collider = getCollidingObject(gw, ball);
if (collider === paddle) {
vy = -vy;
ball.move(vx, vy);
} if (collider === brick) {
vy = -vy;
ball.move(vx, vy);
gw.remove(brick);
}
}
let clickAction = function(e) {
let vy = INITIAL_Y_VELOCITY;
let vx = randomReal(MIN_X_VELOCITY, MAX_X_VELOCITY);
if (randomChance()) vx = -vx;
let step = function() {
if (ball.getX() > 0 && ball.getY() > 0 &&
ball.getX() < gw.getWidth() - BALL_SIZE &&
ball.getY() < gw.getHeight() - BALL_SIZE) {
ball.move(vx, vy);
checkForCollision(brick, paddle);
}
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()) {
clearInterval(timer);
}
};
let timer = setInterval(step, TIME_STEP);
};
gw.addEventListener("click", clickAction);
}
function getCollidingObject(gw, ball) {
let x = ball.getX();
let y = ball.getY();
let object = null;
object = gw.getElementAt(x, y);
if (object !== NULL) {
return object;
}
object = gw.getElementAt(x, y + BALL_SIZE);
if (object !== NULL) {
return object;
}
object = gw.getElementAt(x + BALL_SIZE, y);
if (object !== NULL) {
return object;
}
object = gw.getElementAt(x + BALL_SIZE, y + BALL_SIZE);
if (object !== NULL) {
return object;
}
return NULL;
}
我对以前的代码做了一些小的编辑,但无济于事。请帮帮我。谢谢!