在Java中使用矩形检测侧面碰撞



这是我学习Java的第一周,我正在制作一个矩形相互弹跳的游戏。rx和ry是矩形的坐标,velRX和velRY是它们的x和y速度。我试图使矩形相互反弹(y速度反向),但如果它们在顶部或底部碰撞,则以相同的x速度继续,反之亦然。然而,我不知道如何检测矩形在哪一边碰撞。我能帮忙吗?相关代码

//Checking for collision between Nemesis and Cop
    public boolean checkCollisionOther() {
        Rectangle r1 = rect1.getBoundsNemesis();
        Rectangle r2 = rect2.getBoundsCop();
        if (r1.intersects(r2)){
            collision = true;
            rect1.velRY = -rect1.velRY;
            rect1.velRX = -rect1.velRX;
            rect2.velRY = -rect2.velRY;
            rect2.velRX = -rect2.velRX;
        }
        else
            collision = false;
        return collision;       
    }

您要做的是为两个游戏矩形的每条边创建边界矩形。由于矩形有4条边,因此矩形有4个边界矩形。

你有4个边界矩形为警察和4个边界长方形为敌人。这意味着您必须在一个双for循环中执行16个intersects测试。

当其中一个intersects测试返回true时,您可以确定cop矩形的哪个边和nemesis矩形的哪个边缘发生了碰撞。

下面是一些代码来说明如何创建边界矩形。如果需要,可以将它们设置为大于3个像素。

public List<BoundingRectangle> createBoundingRectangles(Rectangle r) {
    List<BoundingRectangle> list = new ArrayList<BoundingRectangle>();
    int brWidth = 3;
    // Create left rectangle
    Rectangle left = new Rectangle(r.x, r.y, brWidth, r.height);
    list.add(new BoundingRectangle(left, "left"));
    // Create top rectangle
    Rectangle top = new Rectangle(r.x, r.y, r.width, brWidth);
    list.add(new BoundingRectangle(top, "top"));
    // Create right rectangle
    Rectangle right = new Rectangle(r.x + r.width - brWidth, r.y, brWidth,
            r.height);
    list.add(new BoundingRectangle(right, "right"));
    // Create bottom rectangle
    Rectangle bottom = new Rectangle(r.x, r.y + r.height - brWidth,
            r.width, brWidth);
    list.add(new BoundingRectangle(bottom, "bottom"));
    return list;
}
public class BoundingRectangle {
    private Rectangle rectangle;
    private String position;
    public BoundingRectangle(Rectangle rectangle, String position) {
        this.rectangle = rectangle;
        this.position = position;
    }
    public Rectangle getRectangle() {
        return rectangle;
    }
    public String getPosition() {
        return position;
    }
    public boolean intersects(Rectangle r) {
        return rectangle.intersects(r);
    }
}

最新更新