及时预测圆与圆的相交



我需要找出两个圆形物体是否会碰撞,如果是的话,他们会及时碰撞。

我的方法是:

if (Vector3.DistanceSquared(a.Position, b.Position) < Math.Pow(a.Radius + b.Radius,2))
{
return 0;
}
else
{
float result;
for (int t = 1; t < 150; t++)
{
result = Vector3.DistanceSquared(a.Position + t * a.LinearVelocity, b.Position + t * b.LinearVelocity);
if (float.IsInfinity(result))
{
return float.PositiveInfinity;
}
if (result <= Math.Pow(a.Radius+b.Radius,2))
{
return t;
}
}

return float.PositiveInfinity;
}

我显然错过了什么,或者我完全错了,导致结果不像预期的。

我也认为在性能方面循环可能是错误的,但我不确定如何避免它。

如果我们写圆心之间距离的平方:

(x2-x1+t*(vx2-vx1))^2+(y2-y1+t*(vy2-vy1))^2=(r1+r2)^2
let dx = x2-x1, dy = y2-y1, dvx = vx2-vx1, dvy = vy2-vy1, rr = r1+r2
(dx+t*dvx)^2+(dy+t*dvy)^2=rr^2
dx^2+2*dx*t*dvx+t^2*dvx^2+dy^2+2*dy*t*dvy+t^2*dvy^2-rr^2=0
t^2*(dvx^2+dvy^2) + t*(2*dx*dvx+2*dy*dvy) + (dx^2+dy^2-rr^2)=0
t^2*a +             t*b +                   c               =0

这是未知t的二次方程

D = b^2 - 4*a*c
if D<0 there are no collisions
if D=0 there is one touching in moment t = -b/(2*a)
else there are two solutions
t1 = (-b - sqrt(D)) / (2*a)
t2 = (-b + sqrt(D)) / (2*a)

一次或两次可能为负-表示碰撞"已发生在过去">

较小的时间为碰撞时刻,较大的时间为"离开"时刻,我认为这里不需要

相关内容

  • 没有找到相关文章

最新更新