线段/圆交集 – X值似乎错了?

主要编辑

我正在制作一个Breakout克隆,并且在圆和线段之间碰撞检测时遇到困难。

道歉,我以前的问题是挫折和没有睡眠的结果:)

在阅读碰撞检测这篇文章后,我已经将我的碰撞代码重写为以下内容:

// Takes 2 points on a line, a circle centre, and a circle radius // Returns true is collision, false otherwise public Boolean DoesCollide(Vector2 a, Vector2 b, Vector2 c, float rad) { // First up, let's normalise our vectors so the circle is on the origin Vector2 normA = a - c; Vector2 normB = b - c; Vector2 d = normB - normA; // Want to solve as a quadratic equation, need 'a','b','c' components float aa = Vector2.Dot(d, d); float bb = 2 * (Vector2.Dot(normA, d)); float cc = Vector2.Dot(normA,normA)-(rad*rad); // Get determinant to see if LINE intersects double deter = Math.Pow(bb, 2.0) - 4 * aa * cc; if (deter > 0) { // Get t values (solve equation) to see if LINE SEGMENT intersects double t = (-bb - Math.Sqrt(deter)) / (2 * aa); double t2 = (-bb + Math.Sqrt(deter)) / (2 * aa); Boolean match = false; if (0.0 <= t && t <= 1.0) { // Interpolate to get collision point Vector2 collisionPoint = c + Vector2.Lerp(normA, normB, (float)t); match = true; } if (0.0 <= t2 && t2 <= 1.0) { Vector2 collisionPoint2 = c + Vector2.Lerp(normA, normB, (float)t2); match = true; } return match; } else return false; } 

然而,我发现碰撞点的X组件碰到奇怪的结果 – 请参阅以下debugging输出:

 Coll at {X:1033.931 Y:620}, t1 = 0.203759334390812, Normalised = {X:0.8576241 Y:0.5142772} Coll2 at {X:1052.069 Y:620}, t2 = 0.409877029245551, Normalised = {X:0.8615275 Y:0.5077109} Circ cent = {X:1043 Y:610}, rad = 13.5 

正如你所看到的,X分量是圆形中心的任意一边的10px,但是Y分量(620)是Breakout桨的顶部最顶部的像素。 肯定这里的X点不能相隔20个像素,因为Y点的位置?

在计算t0和t1之前,你缺less一个阶段。 它应该看起来更像这样:

 float q; // Holds the solution to the quadratic equation if (bb >= 0) { q = (-bb - Math.Sqrt(deter)) / 2; } else { q = (-bb + Math.Sqrt(deter)) / 2; } float t0 = q / aa; float t1 = cc / q; 

之后,确保t0和t1被sorting。 [编辑]我用行列符做了一个小小的错误,注意它们现在被颠倒了。