bool CircleSegmentIntersect(CL_Vec2f C, float r, CL_Vec2f A, CL_Vec2f B, CL_Vec2f& P) { CL_Vec2f AC = C - A; CL_Vec2f AB = B - A; float ab2 = AB.dot(AB); float acab = AC.dot(AB); float t = acab / ab2; if (t < 0.0f) t = 0.0f; else if (t > 1.0f) t = 1.0f; P = A + AB * t; CL_Vec2f H = P - C; float h2 = H.dot(H); float r2 = r * r; if(h2 > r2) return false; else return true; }
bool IntersectRaySphere(CL_Vec2f p, CL_Vec2f d, rtCircle s, float &t, CL_Vec2f &q) { CL_Vec2f m = p - s.c; float b = m.dot(d); float c = m.dot(m) - s.r * s.r; // Exit if r’s origin outside s (c > 0) and r pointing away from s (b > 0) if (c > 0.0f && b > 0.0f) return false; float discr = b*b - c; // A negative discriminant corresponds to ray missing sphere if (discr < 0.0f) return false; // Ray now found to intersect sphere, compute smallest t value of intersection t = -b - sqrt(discr); // If t is negative, ray started inside sphere so clamp t to zero if (t < 0.0f) t = 0.0f; q=p+(d*t); return true; }