gpt4 book ai didi

java - 碰撞检测问题

转载 作者:搜寻专家 更新时间:2023-10-30 21:33:21 27 4
gpt4 key购买 nike

我的游戏碰撞检测系统有点问题。游戏中有几个相互连接的结构。但是,当它们之间存在另一个结构时,它们不应连接。

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

图片:

BUG

红色标记的节点应该是连接的。

代码:

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,返回判别式 >= 0; 将为真;

强烈建议在我提到的 2 个部分放置一个断点,并在代码执行之前和之后检查您的值,这样您就可以看到数学的进展情况。

此外,Unity API 具有碰撞检测功能。你应该看看那个。 https://docs.unity3d.com/Manual/PhysicsSection.html

希望对您有所帮助。

关于java - 碰撞检测问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41662774/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com