圆与扇形的碰撞检测,算法是这样的:
首先把扇形视作一个圆,排除圆与扇形圆不相交的情况,
然后如果圆心在扇形两条边中间,则必然相交,
剩下的就判断圆是否与两条边相交。
这种算法用到了点与直线的关系,圆与线段的碰撞检测,圆与圆的碰撞检测等。
圆与扇形碰撞检测实现代码如下:
#ifndef __CIRCLE_FAN_INTERSECTION_H__
#define __CIRCLE_FAN_INTERSECTION_H__
#include "point_in_triangle_test.h"
#include "circle_lineseg_intersection.h"
// 判断圆与扇形是否相交
// 圆心p(x, y), 半径r, 扇形圆心p1(x1, y1), 扇形正前方最远点p2(x2, y2), 扇形夹角弧度值theta(0,pi)
bool IsCircleIntersectFan(float x, float y, float r, float x1, float y1, float x2, float y2, float theta)
{
// 计算扇形正前方向量 v = p1p2
float vx = x2 - x1;
float vy = y2 - y1;
// 计算扇形半径 R = v.length()
float R = sqrt(vx * vx + vy * vy);
assert(R > 0.00001f);
// 圆不与扇形圆相交,则圆与扇形必不相交
if ((x - x1) * (x - x1) + (y - y1) * (y - y1) > (R + r) * (R + r))
return false;
assert(theta > 0.00001f && theta < 3.1416f);
// 根据夹角 theta/2 计算出旋转矩阵,并将向量v乘该旋转矩阵得出扇形两边的端点p3,p4
float h = theta * 0.5f;
float c = cosf(h);
float s = sinf(h);
float x3 = x1 + (vx * c - vy * s);
float y3 = y1 + (vx * s + vy * c);
float x4 = x1 + (vx * c + vy * s);
float y4 = y1 + (-vx * s + vy * c);
// 如果圆心在扇形两边夹角内,则必相交
float d1 = EvaluatePointToLine(x, y, x1, y1, x3, y3);
float d2 = EvaluatePointToLine(x, y, x4, y4, x1, y1);
if (d1 >= 0 && d2 >= 0)
return true;
// 如果圆与任一边相交,则必相交
if (IsCircleIntersectLineSeg(x, y, r, x1, y1, x3, y3))
return true;
if (IsCircleIntersectLineSeg(x, y, r, x1, y1, x4, y4))
return true;
return false;
}
#endif // __CIRCLE_FAN_INTERSECTION_H__
其中EvaluatePointToLine的实现详见: http://blog.csdn.net/zaffix/article/details/25005057
IsCircleIntersectLineSeg的实现详见: http://blog.csdn.net/zaffix/article/details/25160505