我的游戏碰撞系统不适用于多个板块

My game collision system doesn't work on more than one tile

我正在为我的游戏开发一个碰撞系统,但是我无法让它工作,如果我添加不止一堵墙(这是我正在渲染的对象),碰撞系统不会工作,我可以通过街区。

然而,如果我只留下一堵墙,碰撞就会正常进行,或者如果在循环结束时我添加了一个中断; 碰撞有效,但仅在地图的第一面墙上发生碰撞,其他墙壁没有碰撞。

有大神知道怎么解决吗?我一直试图解决它 2 天,我不能。

    public boolean checkCollisionWall(int xnext, int ynext){
        int[] xpoints1 = {xnext+3,xnext+3,xnext+4,xnext+3,xnext+3,xnext+4,xnext+10,xnext+11,xnext+11,xnext+10,xnext+11,xnext+11};
        int[] ypoints1 = {ynext+0,ynext+8,ynext+9,ynext+11,ynext+12,ynext+15,ynext+15,ynext+12,ynext+11,ynext+9,ynext+8,ynext+0};
        int npoints1 = 12;
        Polygon player = new Polygon(xpoints1,ypoints1,npoints1);
        Area area = new Area(player);
        for(int i = 0; i < Game.walls.size(); i++){
            Wall atual = Game.walls.get(i);
            int[] xpoints2 = {atual.getX(),atual.getX(),atual.getX()+16,atual.getX()+16};
            int[] ypoints2 = {atual.getY(),atual.getY()+16,atual.getY()+16,atual.getY()};
            int npoints2 = 4;
            Polygon Wall = new Polygon(xpoints2,ypoints2,npoints2);
            area.intersect(new Area(Wall));
            if(area.isEmpty()){
                return true;
            }
        }
    return false;
    }

我很确定问题出在这个电话上:

area.intersect(new Area(Wall));

这是该方法的 JavaDoc:

public void intersect(Area rhs)

Sets the shape of this Area to the intersection of its current shape and the shape of the specified Area. The resulting shape of this Area will include only areas that were contained in both this Area and also in the specified Area.

所以 area,代表你的玩家的形状,每次测试都会修改一堵墙,这就是为什么它只适用于一堵墙。

您可以通过简单地将播放器 Area 作为调用的参数来解决此问题,如:

Area wallArea = new Area(Wall); 
wallArea.intersect(area);
if(wallArea.isEmpty()){
    return true;
}

顺便说一下,这个逻辑是反的吧。您不想检查生成的区域是否为空,即玩家和墙之间是否有重叠?

另一种选择,如果每个 Wall 实际上是一个矩形,则改为使用此 Area 方法:

public boolean intersects(double x, double y, double w, double h)

Tests if the interior of the Shape intersects the interior of a specified rectangular area. The rectangular area is considered to intersect the Shape if any point is contained in both the interior of the Shape and the specified rectangular area.

像这样:

if(area.intersects(atual.getX(), atual.getY(), 16, 16)) {
    return true;
}

因为这避免了为每面墙创建一个 Area 对象,相交测试将变得更加简单和快速。