您的位置:首页 > 其它

圆与线段碰撞检测

2016-02-16 15:03 274 查看
圆与线段的碰撞检测算法利用了一个向量在另一个向量的投影的原理。

假设向量p1p为v1, 向量p1p2为v2,p0为v1在v2上的投影点,则p1p0为v1在v2上的投影。

两个向量点乘v1.dot(v2) = v1.length() * v2.length() * cos(theta) = x1 * x2 + y1 * y2,当v2经过单位化后,点乘的结果就变成的投影向量p1p0的长度,设为u。

当p位于p1左侧时,theta角度大于90度,cos值为负,所以u <= 0;当p位于p2右侧时,u >= v2.length()。

依此可以算出到圆心p到线段上距离最近的点,如果到该点距离小于圆半径r,则圆与线段相交。



圆与线段碰撞检测的算法实现:

#ifndef __CIRCLE_LINESEG_INTERSECTION_H__
#define __CIRCLE_LINESEG_INTERSECTION_H__

#include
#include

// 圆与线段碰撞检测
// 圆心p(x, y), 半径r, 线段两端点p1(x1, y1)和p2(x2, y2)
bool IsCircleIntersectLineSeg(float x, float y, float r, float x1, float y1, float x2, float y2)
{
float vx1 = x - x1;
float vy1 = y - y1;
float vx2 = x2 - x1;
float vy2 = y2 - y1;

assert(fabs(vx2) > 0.00001f || fabs(vy2) > 0.00001f);

// len = v2.length()
float len = sqrt(vx2 * vx2 + vy2 * vy2);

// v2.normalize()
vx2 /= len;
vy2 /= len;

// u = v1.dot(v2)
// u is the vector projection length of vector v1 onto vector v2.
float u = vx1 * vx2 + vy1 * vy2;

// determine the nearest point on the lineseg
float x0 = 0.f;
float y0 = 0.f;
if (u <= 0)
{
// p is on the left of p1, so p1 is the nearest point on lineseg
x0 = x1;
y0 = y1;
}
else if (u >= len)
{
// p is on the right of p2, so p2 is the nearest point on lineseg
x0 = x2;
y0 = y2;
}
else
{
// p0 = p1 + v2 * u
// note that v2 is already normalized.
x0 = x1 + vx2 * u;
y0 = y1 + vy2 * u;
}

return (x - x0) * (x - x0) + (y - y0) * (y - y0) <= r * r;
}

#endif // __CIRCLE_LINESEG_INTERSECTION_H__


原文出处:点击打开链接
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: