我有一条从A到B的直线和一个半径为R的圆。
检查直线是否与圆相交的好算法是什么?它是在什么坐标上沿着圆圈的边缘发生的?
发布于 2009-07-03 21:57:28
似乎没有人考虑投影,我是不是完全偏离了轨道?
将矢量AC
投影到AB
上。投影矢量AD
给出了新的点D
。
如果D
和C
之间的距离小于(或等于) R
,我们就有一个交集。
如下所示:
发布于 2009-07-06 16:55:52
我将使用该算法计算点(圆心)和直线(AB线)之间的距离。然后,可以使用它来确定直线与圆的交点。
假设我们有点A,B,C,Ax和Ay是A点的x和y分量。B和C也是一样。标量R是圆的半径。
该算法要求A、B和C是不同的点,并且R不是0。
下面是算法
// compute the euclidean distance between A and B
LAB = sqrt( (Bx-Ax)²+(By-Ay)² )
// compute the direction vector D from A to B
Dx = (Bx-Ax)/LAB
Dy = (By-Ay)/LAB
// the equation of the line AB is x = Dx*t + Ax, y = Dy*t + Ay with 0 <= t <= LAB.
// compute the distance between the points A and E, where
// E is the point of AB closest the circle center (Cx, Cy)
t = Dx*(Cx-Ax) + Dy*(Cy-Ay)
// compute the coordinates of the point E
Ex = t*Dx+Ax
Ey = t*Dy+Ay
// compute the euclidean distance between E and C
LEC = sqrt((Ex-Cx)²+(Ey-Cy)²)
// test if the line intersects the circle
if( LEC < R )
{
// compute distance from t to circle intersection point
dt = sqrt( R² - LEC²)
// compute first intersection point
Fx = (t-dt)*Dx + Ax
Fy = (t-dt)*Dy + Ay
// compute second intersection point
Gx = (t+dt)*Dx + Ax
Gy = (t+dt)*Dy + Ay
}
// else test if the line is tangent to circle
else if( LEC == R )
// tangent point to circle is E
else
// line doesn't touch circle
发布于 2015-08-19 19:25:34
我写了一个小脚本,通过将圆的中心点投影到直线上来测试交叉点。
vector distVector = centerPoint - projectedPoint;
if(distVector.length() < circle.radius)
{
double distance = circle.radius - distVector.length();
vector moveVector = distVector.normalize() * distance;
circle.move(moveVector);
}
http://jsfiddle.net/ercang/ornh3594/1/
如果需要检查与线段的碰撞,还需要考虑圆心到起点和终点的距离。
vector distVector = centerPoint - startPoint;
if(distVector.length() < circle.radius)
{
double distance = circle.radius - distVector.length();
vector moveVector = distVector.normalize() * distance;
circle.move(moveVector);
}
https://stackoverflow.com/questions/1073336
复制相似问题