Java Breakout游戏弹跳球

时间:2012-06-28 01:32:43

标签: java 2d game-engine breakout

我正试图在java中制作突破性的游戏。当击中石块和蝙蝠时球会反弹,但在击中墙壁后球不会弹。请参阅此粘贴以了解我使用的内容。

http://pastebin.com/pkGsCBMa

有人能发现代码中的错误......

由于

编辑:当打印出速度时,我得到了这个输出。

vx 0.0     vy  0.0
vx 0.02    vy -0.02
vx 0.02    vy -0.02
vx 0.02    vy -0.02
vx 0.02    vy -0.02
vx 0.02    vy -0.02
vx 0.02    vy -0.02
vx 0.02    vy -0.02
vx 0.02    vy -0.02
vx 0.02    vy -0.02
vx 0.02    vy -0.02
vx 0.02    vy -0.02
vx 0.02    vy -0.02
vx 0.02    vy -0.02
vx 0.02    vy -0.02
vx 0.02    vy -0.02
vx 0.02    vy -0.02
vx 0.02    vy -0.02
vx 0.02    vy -0.02
vx 0.02    vy -0.02
vx 0.02    vy -0.02
vx 0.02    vy -0.02
vx 0.02    vy -0.02
vx 0.02    vy -0.02
vx 0.02    vy -0.02
vx 0.02    vy -0.02
vx 0.02    vy -0.02
vx 0.02    vy -0.02
vx 0.0     vy  0.0
vx 0.02    vy -0.02
vx 0.02    vy -0.02
vx 0.02    vy -0.02
vx 0.02    vy -0.02

修改

这是解决方案。我已经将bounce()方法更改为此。

/**
 * This object bounces back from the other object in a natural way. Please
 * realize that the bounce is not completely accurate because this depends
 * on many properties. But in many situations the effect is good enough. Had
 * some bugs in pixel perfect detection mode if the image has a larger area
 * of complete alpha. If using PPCD, make the object fit the image size by
 * removing the alpha and resizing the image.
 */
public void bounce(GObject other){
    int xd = (int) ((other.x + other.getWidth() / 2) - (x + getWidth() / 2));
    int yd = (int) ((other.y + other.getHeight() / 2) - (y + getHeight() / 2));
    if (xd < 0) {
        xd = -xd;
    }
    if (yd < 0) {
        yd = -yd;
    }
    if (xd > yd) {
        dx = -dx;
    } else {
        dy = -dy;
    }
}

2 个答案:

答案 0 :(得分:4)

此问题的一个常见原因是碰撞对象重叠并陷入连续碰撞状态。

因此球相对较快地移动并与一个块发生碰撞。然而,由于模拟是离散的,球实际上会稍微进入块。然后,您可以正确检测到碰撞并反转速度。但是在下一个更新周期中,无论出于何种原因,球可能仍然位于区块内。因此程序检测到另一个“碰撞”并再次反转速度。

结果是你的球在挡块的边缘抖动,不断地反转速度。

答案 1 :(得分:3)

bounce函数中,ifelse if并未涵盖所有值。我建议您将>替换为>=或{ {1}} <