首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >圆线段碰撞检测算法?

圆线段碰撞检测算法?
EN

Stack Overflow用户
提问于 2009-07-02 17:15:10
回答 22查看 163.4K关注 0票数 213

我有一条从A到B的直线和一个半径为R的圆。

检查直线是否与圆相交的好算法是什么?它是在什么坐标上沿着圆圈的边缘发生的?

EN

回答 22

Stack Overflow用户

发布于 2009-07-03 21:57:28

似乎没有人考虑投影,我是不是完全偏离了轨道?

将矢量AC投影到AB上。投影矢量AD给出了新的点D

如果DC之间的距离小于(或等于) R,我们就有一个交集。

如下所示:

票数 146
EN

Stack Overflow用户

发布于 2009-07-06 16:55:52

我将使用该算法计算点(圆心)和直线(AB线)之间的距离。然后,可以使用它来确定直线与圆的交点。

假设我们有点A,B,C,Ax和Ay是A点的x和y分量。B和C也是一样。标量R是圆的半径。

该算法要求A、B和C是不同的点,并且R不是0。

下面是算法

代码语言:javascript
复制
// 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
票数 52
EN

Stack Overflow用户

发布于 2015-08-19 19:25:34

我写了一个小脚本,通过将圆的中心点投影到直线上来测试交叉点。

代码语言:javascript
复制
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/

如果需要检查与线段的碰撞,还需要考虑圆心到起点和终点的距离。

代码语言:javascript
复制
vector distVector = centerPoint - startPoint;
if(distVector.length() < circle.radius)
{
    double distance = circle.radius - distVector.length();
    vector moveVector = distVector.normalize() * distance;
    circle.move(moveVector);
}

https://jsfiddle.net/ercang/menp0991/

票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1073336

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档