Nevon
January 28th, 2010, 11:29 AM
I have a finite straight line somewhere. I know its ending point coordinates. I also have a circle of which I also know the coordinates (of the center) and also the radius.
Now I need to figure out whether or not the circle intersects the line somewhere. I've found several examples online, but I haven't been able to get one to work properly.
The simplest method I've found so far looks like this, but the syntax is unfamiliar to me, so I'm having problems reimplementing it:
bool IntersectCircleSegment(
const Vector2& c, // center
float r, // radius
const Vector2& p1, // segment start
const Vector2& p2) // segment end
{
Vector2 dir = p2 - p1;
Vector2 diff = c - p1;
float t = diff.Dot(dir) / dir.Dot(dir);
if (t < 0.0f)
t = 0.0f;
if (t > 1.0f)
t = 1.0f;
Vector2 closest = p1 + t * dir;
Vector2 d = c - closest;
float distsqr = d.Dot(d);
return distsqr <= r * r;
}
If someone could walk me through this code and explain it line by line (or something like that anyway) that would be great. I'm having some problems with the dot product method and I don't quite know how subtraction of vectors work. In my code I have the various coordinates (at least when I send them to the function) as their own variables, rather than lumped together in a vector.
Now I need to figure out whether or not the circle intersects the line somewhere. I've found several examples online, but I haven't been able to get one to work properly.
The simplest method I've found so far looks like this, but the syntax is unfamiliar to me, so I'm having problems reimplementing it:
bool IntersectCircleSegment(
const Vector2& c, // center
float r, // radius
const Vector2& p1, // segment start
const Vector2& p2) // segment end
{
Vector2 dir = p2 - p1;
Vector2 diff = c - p1;
float t = diff.Dot(dir) / dir.Dot(dir);
if (t < 0.0f)
t = 0.0f;
if (t > 1.0f)
t = 1.0f;
Vector2 closest = p1 + t * dir;
Vector2 d = c - closest;
float distsqr = d.Dot(d);
return distsqr <= r * r;
}
If someone could walk me through this code and explain it line by line (or something like that anyway) that would be great. I'm having some problems with the dot product method and I don't quite know how subtraction of vectors work. In my code I have the various coordinates (at least when I send them to the function) as their own variables, rather than lumped together in a vector.