我需要找出兩個圓形物體是否會碰撞,如果是,它們何時會發生碰撞。
我的方法是這樣的:
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;
}
我顯然遺漏了一些東西,或者我完全錯了,因為結果不符合預期。
我也認為回圈可能是錯誤的,但我不確定如何避免它。
uj5u.com熱心網友回復:
如果我們寫出圓心之間的平方距離:
(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)
一次或兩次都可能是負數 - 意味著碰撞“過去”
較小的時間是碰撞的時刻,較大的時間-“離開”的時刻,我認為這里不需要
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/495354.html