如何修复坏的二维碰撞

时间:2016-05-26 20:12:04

标签: javascript canvas 2d collision-detection game-physics

我在一个我正在研究的JavaScript画布游戏中有关于2D物理的问题。在我的游戏中,我使用以下代码来检测球和砖(矩形)之间的碰撞。碰撞代码正在工作,但球在它消失之前穿过物体,允许球穿过砖场并摧毁大部分砖块。

总之,我怎样才能让球不会穿过砖块?

以下是用于碰撞检测的代码:

if(this.enabled && 
   ball.x + ball.vx < this.x + BRICK_WIDTH &&
   ball.x + ball.vx + ball.radius > this.x &&
   ball.y + ball.vy < this.y + BRICK_HEIGHT &&
   ball.y + ball.vy + ball.radius > this.y) {
    ball.vy = -ball.vy;
    this.enabled = false;
}

Here is a video of the faulty collision detection

Also if you would like to, you can try it yourself

注意球是如何轻微穿过青砖的?

2 个答案:

答案 0 :(得分:0)

if(this.enabled && 
   ball.x + ball.vx - ball.radius < this.x + BRICK_WIDTH &&
   ball.x + ball.vx + ball.radius > this.x &&
   ball.y + ball.vy - ball.radius < this.y + BRICK_HEIGHT &&
   ball.y + ball.vy + ball.radius > this.y) {
    ball.vy = -ball.vy;
    this.enabled = false;
}

你没有在两个距离计算中加入球的半径。我没有其他代码,所以你必须验证它是否有效。

答案 1 :(得分:0)

在角落中,在检查过程中,您将添加半径直径的一半。这意味着在与顶部碰撞时,球必须穿过砖块一半才能达到标准。

尝试

     ball.y + ball.vy + ball.radius*2 > this.y

也在其他x检查中......