我有一个小问题,我的碰撞检测系统的游戏。游戏中有几个相互连接的结构。然而,当它们之间有另一个结构时,它们不应该连接。
由于一些奇怪的原因,有时它无法连接到直接相邻的结构,当有一个结构在其后面的一条直线。很少会产生其他奇怪的联系。
图片:

红色标记的节点应该是连接的。
代码:
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
}(我只为文本添加了注释,因此如果它们会导致编译错误,请忽略它们)。
有人能告诉我我做错了什么吗?
发布于 2017-03-02 18:52:59
这里可能有几个问题:
First:如Marat所说:b可能返回值0。如果您的getX()和getY()返回x1和y1,则会发生这种情况。如果是这样的话,您实际上是在这样做:(2dx * 0) + (2dy * 0)。如果是这样的话,它会对你以后的方程产生负面影响。
第二:更有可能的是,您总是根据您的最后公式返回true:
double discriminant = b * b - 4 * a * c;
//This breaks down to discriminant = b^2 * 4ac即使此时b为0,只要a或c的值大于0,return discriminant >= 0;也将为真;
我强烈建议在我提到的两个部分中放置一个断点,并在代码执行之前和之后检查您的值,这样您就可以看到数学上发生了什么。
此外,Unity还具有冲突检测功能。你应该看看这个。https://docs.unity3d.com/Manual/PhysicsSection.html
希望这能有所帮助。
发布于 2017-03-01 22:22:29
假设:1如果我正确理解,这些都是某些结构类的方法。2 hasStructureInRangeWithoutObstaclesInBetween是collidesWithLine的唯一调用者,至少是这样提出问题的。
因为(2) b总是0。我觉得这不是你的本意。请重新访问您的collidesWithLine方法。
https://stackoverflow.com/questions/41662774
复制相似问题