I am in the process of learning collision detection and am currently writing some bounding volumes for 2d applications. So far I have the AABB, OBB, and Bounding Sphere equivalents written in 2D for XNA. Unfortunately, I am having this odd issue in my BC (Bounding Circle) class when trying to compute the distance between the circle and a point.
My circles are represented by c and r. c is a Vector2 defining the center point of the circle and r is a scalar float defining the radius of the circle.
I know the distance between a point and the closest point on a circle to that point can be found in the following way. You find the distance between the center and the point by subtracting the two vectors and finding the length of the difference. Then, subtracting this distance by the radius.
My source code for my DistanceToPoint(Vector2 point) method is shown below. Note, if the point is inside the circle, the distance should be returned as 0.
public float DistanceToPoint(Vector2 point) {
float dist = (c - point).Length();
if (dist <= r)
return 0.0f;
else
return dist - r;
}
Now, I'd also like to have a squared version of the same query since the square root operation is pretty expensive and this can speed up some checks. I think this should be done by finding the squared length of the same difference and subtracting this by the squared radius. However, all my tests show my DistanceToPointSquared(Vector2 point) method is not producing the right results. Here is my source code for this method.
public float DistanceToPointSquared(Vector2 point) {
float sqDist = (c - point).LengthSquared();
float sqRadius = r * r;
if (sqDist <= sqRadius)
return 0.0f;
else
return sqDist - sqRadius;
}
If anyone knows what I'm doing wrong it would be greatly appreciated...because I'd really like to get going and try these out in a spatially partitioned scene :). Thank you for your time.