【发布时间】:2017-05-30 11:42:35
【问题描述】:
我的游戏碰撞检测系统有点问题。 游戏中有几个相互连接的结构。但是,当它们之间存在另一个结构时,它们不应连接。
由于某些奇怪的原因,当在它们后面的直线上有一个结构时,它有时无法连接到直接相邻的结构。很少会产生其他奇怪的联系。
图片:
红色标记的节点应该是连接的。
代码:
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
}
(我只为本文添加了 cmets,如果它们会导致编译错误,请忽略它们)。
谁能告诉我我做错了什么?
【问题讨论】:
-
好吧,我真的需要至少一个提示...而且我不想造成重复...
-
也许这有点宽泛。您能解释一下您使用的数学方法以及您认为问题可能出在哪里吗?
-
我的建议是为
collidesWithLine()编写一个单元测试,以确定您是否放错了操作符。也很难看出计算实际做了什么,所以很容易混淆 '+' 和 '*' 例如。除此之外,您的 sn-p 还没有显示完整的图片。collidesWithLine()范围内的this是什么? javadoc 注释也可以提供帮助。 -
两点之间的距离:
sqrt( (x2-x1)^2 + (y2-y1)^2),但您正在计算没有平方根的距离。这是我很容易发现的,代码中可能还有其他缺陷。
标签: java collision-detection collision