您好,我正在尝试计算Circle-LineSegment碰撞(在2D坐标空间中)。
我想在我的特工移动时检测到碰撞,所以我正在逐步执行它的移动-> agentPosition
是现在的特工所在的位置,agentPosition + agentDelta
是它在此步骤中要移动的位置。 / p>
该行定义为FVertex
(是的,我知道这个名字很糟糕)testEdge
(它有2个点A
和B
)。
以(agentPosition + agentDelta)
为圆心,以agentRadius
为半径定义圆。
我试图找到一个碰撞点(这是2个可能的交叉点的平均值)并计算所需的参数:
碰撞时间({0.0f,1.0f}) CollisionPoint(碰撞时圆的位置) ImpactPoint(平均碰撞点)
这是我尝试过的,但是我没有运气:(
我得到的结果是负数或大于1.0f
的时间,有时,该碰撞点也位于线段和其他有趣工件的另一侧。
如果您能帮助我在这里找到我在做什么错,我将不胜感激。
static bool CheckAgentEdgeCollision(FVertex testEdge, FVector agentPosition, FVector agentDelta, float agentRadius, FCollisionResult2Dplease& outCollisionResult, UWorld* world = nullptr)
{
agentPosition.Z = 0.0f;
agentDelta.Z = 0.0f;
testEdge.B.Z = 0.0f; testEdge.A.Z = 0.0f;
FVector D = testEdge.B - testEdge.A;
FVector d = testEdge.A - (agentPosition + agentDelta);
float a = D | D; // Operator | is Dot Product
float b = (d | D) * 2.0f;
float c = (d | d) - FMath::Square(agentRadius);
float disc = b * b - 4.0f * a * c;
if (disc < KINDA_SMALL_NUMBER)
{
return false;
}
float sqrtDisc = FastSQRoot(disc);
float invA = 1.0f / ( a * 2.0f );
float t0 = (-b - sqrtDisc) * invA;
float t1 = (-b + sqrtDisc) * invA;
FVector poin1 = FVector::ZeroVector;
FVector poin2 = FVector::ZeroVector;
poin1 = testEdge.A + t0 * D;
poin2 = testEdge.A + t1 * D;
bool p1 = true;
bool p2 = true;
if(t0 > 1.0f || t0 < 0.0f)
{
//disregard
p1 = false;
}
if (t1 > 1.0f || t1 < 0.0f)
{
p2 = false;
}
if(!p1 && !p2)
{
return false;
}
else if(!p1)
{
poin1 = poin2;
}
else if (!p2)
{
poin2 = poin1;
}
float invRadius = 1.0f / agentRadius;
agentRadius += 5.0f;
//Average the points:
FVector impactPoint = (poin1 + poin2) / 2.0f;
FVector directionToCircle = agentPosition - impactPoint;
FastNormalize(directionToCircle);
FVector collisionPoint = directionToCircle * agentRadius + impactPoint;
float distToCollision = FastSQRoot(agentPosition.DistSquared2D(agentPosition, collisionPoint));
float speed = FastSQRoot(agentDelta.SizeSquared2D());
float outTime = 0.0f;
if (speed != 0.0f)
{
outTime = distToCollision / speed;
}
outCollisionResult.m_bIsPawn = false;
outCollisionResult.m_edge = testEdge;
outCollisionResult.m_normal = directionToCircle;
outCollisionResult.m_collisionPoint = collisionPoint;
outCollisionResult.m_time = outTime;
outCollisionResult.m_bHit = true;
outCollisionResult.m_impactPoint = impactPoint;
outCollisionResult.m_binPenetration = outTime < 0.0f;
return true;
}