我的游戏碰撞检测系统有一个小问题。
游戏中有几个相互连接的结构。但是,如果它们之间存在其他结构,则它们不应连接。

由于某些奇怪的原因,当在它们后面的直线中有结构时,有时有时无法连接到直接相邻的结构。很少会产生其他怪异的联系。

图片:



带有红色标记的节点应该已连接。

代码:

public void drawConnections(Graphics g) {
    ArrayList<EnergyContainer> structurecopy = (ArrayList<EnergyContainer>) Mainclass.structures.clone(); //all structures in a list
    structurecopy.remove(this); //as we are member of the list
    structurecopy.removeIf(t -> (!hasStructureInRangeWithoutObstaclesInBetween(t)));
    structurecopy.removeIf(t -> !t.receivesEnergyfromNeighbors()); //unimportant check if it is allowed to connect (its working)
    structurecopy.forEach(t -> drawConnectionTo(t, g)); //also works fine
}

public boolean hasStructureInRangeWithoutObstaclesInBetween(Structure structureWhichShouldBeInRange) {
    // if in Range
    if (getRange() >= Math.hypot(structureWhichShouldBeInRange.getX() - getX(),
            structureWhichShouldBeInRange.getY() - getY())){ //checks if structure is in range
        ArrayList<EnergyContainer> structureclone = (ArrayList<EnergyContainer>) Mainclass.structures.clone();
        structureclone.remove(this); //again removes itself from the list
        structureclone.remove(structureWhichShouldBeInRange); //also removes target - so it doesn't block itself
        structureclone.removeIf(t -> !t.collidesWithLine(this.getX(), structureWhichShouldBeInRange.getX(),
                this.getY(), structureWhichShouldBeInRange.getY())); //removes it when it does not collide
        return structureclone.size() == 0; //returns true when no collisions are found
    }
    return false;
}

public boolean collidesWithLine(int x1, int x2, int y1, int y2) {
    // Line Segment - Circle Collision Detection
    double dx = x2 - x1;
    double dy = y2 - y1;
    double a = dx * dx + dy * dy; //this is the distance
    double b = 2 * dx * (x1 - getX()) + 2 * dy * (y1 - getY());
    double c = getX() * getX() + getY() * getY() + x1 * x1 + y1 * y1 - 2 * (getX() * x1 + getY() * y1)
            - getCollisionRadius() * getCollisionRadius();
    double discriminant = b * b - 4 * a * c;
    return discriminant >= 0; // no intersection -> discriminant <0

}

(我仅添加了此文本的注释,因此如果它们会引起编译错误,请忽略它们)。

有人可以告诉我我在做什么错吗?

最佳答案

这里可能有几个问题:

首先:如Marat所述:b可能返回值0。如果getX()getY()返回x1y1,则可能会发生这种情况。如果是这样,您实际上就是在这样做:(2dx * 0) + (2dy * 0)。如果真是这样,可能会对您以后的方程式产生负面影响。

其次:很有可能,您是总是根据您的最终等式返回true:

double discriminant = b * b - 4 * a * c;
//This breaks down to discriminant = b^2 * 4ac

即使此时b为0,只要ac的值都大于0,return discriminant >= 0;将为true;否则,ojit_code将为true。

我强烈建议在我提到的2个部分插入一个断点,并在代码执行之前和之后检查您的值,以便您可以了解数学的情况。

另外,Unity API具有冲突检测功能。您应该注意这一点。 https://docs.unity3d.com/Manual/PhysicsSection.html

希望能有所帮助。

10-04 18:13
查看更多