I am trying to learn how to mathematically define and detect "hits" on a 2D Capsule.
I am defining and detecting hits on a 2D Circle. Here's my class:
class Circle
{
private double xpos;
private double ypos;
private double radius;
public Circle(double x, double y, double r)
{
xpos = x;
ypos = y;
radius = r;
}
public bool HitCircle(double x, double y)
{
bool hit = false;
double distance = Math.Pow(x - xpos, 2) + Math.Pow(y - ypos, 2);
if (distance <= radius * radius) hit = true;
return hit;
}
}
The circle is an x and y position and a radius. The HitCircle
function is the C# implementation of the distance formula.
A capsule is defined as 4 points and a radius:
class Capsule
{
double x1pos;
double y1pos;
double x2pos;
double y2pos;
double radius;
public Capsule(double x1, double y1, double x2, double y2, double r)
{
x1pos = x1;
y1pos = y1;
x2pos = x2;
y2pos = y2;
radius = r;
}
public bool HitCapsule(double x, double y)
{
bool hit = false;
//?? This is where I need help
return hit;
}
}
I need help understanding and implementing the math for the HitCapsule
function in the capsule class.
As I understand it, a capsule is like a circle, except instead of having a radius around a single point, it has a radius around a line segment.
For now I'm just trying wrap my brain around some of these geometric definitions. I may try my hand at turning this into a simple raytracer in the future but I wanted to get straight to these math parts.
Thanks.
I don't know if this is helpful, but here's my 2d "raytracer." It draws the circle to the console using ascii. It's helpful to show me that I've implemented the math correctly.
static void Main(string[] args)
{
double aimx = 30;
double aimy = 8;
Circle circle = new Circle(45, 13, 12);
bool hit = circle.HitCircle(aimx, aimy);
Console.WriteLine("Did we hit? {0}", hit);
for(int y = 26; y >= 0; y--)
{
for(int x = 0; x < 90; x++)
{
if(x == aimx && y == aimy) //Draw target
{
Console.Write("X");
}
else if(circle.HitCircle(x, y)) //Draw all circle hits
{
Console.Write("#");
}
else
{
Console.Write("-");
}
}
Console.Write('\n');
}
Console.Read();
}
}
Point to capsule intersection is a case of calculating the distance of the point to the line segment that defines the capsule. If that's <= r then you intersect.
There's a question here that shows how to find that distance, but it does assume a familiarity with vectors and the dot product.