Search code examples
c++mathformulagame-enginequadratic

how is the quadratic formula used in game coding?


hello guys i am game programmer from korea. and just today i found a some code that use the QUADRATIC formula for calculating something. here is code

hduVector3Dd p = startPoint;
hduVector3Dd v = endPoint - startPoint;

// Solve the intersection implicitly using the quadratic formula.
double a = v[0]*v[0] + v[1]*v[1] + v[2]*v[2];
double b = 2 * (p[0]*v[0] + p[1]*v[1] + p[2]*v[2]);
double c = p[0]*p[0] + p[1]*p[1] + p[2]*p[2] - m_radius * m_radius;

double disc = b*b - 4*a*c;

// The scale factor that must be applied to v so that p + nv is
// on the sphere.
double n;
if(disc == 0.0)
{
    n = (-b)/(2*a);
}
else if(disc > 0.0)
{
    double posN = (-b + sqrt(disc))/(2*a);
    double negN = (-b - sqrt(disc))/(2*a);
    n = posN < negN ? posN : negN;
}
else
{
    return false;
}

// n greater than one means that the ray defined by the two points
// intersects the sphere, but beyond the end point of the segment.
// n less than zero means that the intersection is 'behind' the
// start point.
if(n > 1.0 || n < 0.0)
{
    return false;
}

this is the part of function that checking SOMETHING for sphere shape. and i couldn't figure out why use QUADRATIC FORMULA for calculating SOMETHING.

any idea, will be preciated i just really wanna know, understand and reuse it for my code in the future^^


Solution

  • It looks like it is doing a line-sphere collision check.

    I'm not exactly sure where one would use this though(I could be dumb xD)