我在游戏中的碰撞检测系统中遇到了一些问题。游戏中有几个结构物相互连接,但是当它们之间有其他结构物时,它们不应该连接。
但是,由于某种奇怪的原因,有时候直接相邻的结构物之间无法连接,而在它们后面的直线上有另一个结构物。很少情况下会产生其他奇怪的连接。
图片如下:
红色标记的节点应该被连接。
代码如下:
但是,由于某种奇怪的原因,有时候直接相邻的结构物之间无法连接,而在它们后面的直线上有另一个结构物。很少情况下会产生其他奇怪的连接。
图片如下:
红色标记的节点应该被连接。
代码如下:
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
}
有人能告诉我哪里出了问题吗?
collidesWithLine()
编写单元测试,以查明是否错放了运算符。很难看出计算实际上在做什么,因此很容易混淆 '+' 和 '*'。除此之外,您的片段还没有展示完整的情况。在collidesWithLine()
的作用域中,this
是什么?Javadoc 注释也可以帮助解决这个问题。 - SME_Devsqrt((x2-x1)^2 + (y2-y1)^2)
,但是你计算的距离没有开平方。这是我能轻易发现的问题,代码中可能还存在其他缺陷。 - ahoxhagetX()
、getY()
和getCollisionRadius()
的具体内容吗?如果我们不知道这些函数返回的值是什么,就很难判断哪里出了问题。 - Uchiha Itachi