圆与三角形之间的碰撞检测算法可以综合运用之前写过的基本图形间的碰撞检测算法。
如果圆心在三角形内,则三角形与圆必然相交,转换为判断点在三角形内,参考:判断点是否在三角形内;
如果圆与三角形任一条边相交,则三角形与圆必然相交,转换为圆与线段相交,参考:圆与线段碰撞检测;
算法实现如下:
#ifndef __CIRCLE_TIRANGLE_INTERSECTION_H__
#define __CIRCLE_TIRANGLE_INTERSECTION_H__
#include "point_in_triangle_test.h"
#include "circle_lineseg_intersection.h"
// 圆与三角形碰撞检测
// 圆心(x, y), 半径r,三角形三个顶点(x1, y1),(x2, y2), (x3, y3)
bool IsCircleIntersectTriangle(float x, float y, float r, float x1, float y1, float x2, float y2, float x3, float y3)
{
// 圆心在三角形内
if (IsPointInTriangle(x, y, x1, y1, x2, y2, x3, y3))
return true;
// 圆与三角形任一条边碰撞
if (IsCircleIntersectLineSeg(x, y, r, x1, y1, x2, y2))
return true;
if (IsCircleIntersectLineSeg(x, y, r, x2, y2, x3, y3))
return true;
if (IsCircleIntersectLineSeg(x, y, r, x3, y3, x1, y1))
return true;
return false;
}
#endif // __CIRCLE_TIRANGLE_INTERSECTION_H__