您的位置:首页 > 其它

点跟多边形的碰撞检测

2014-03-12 15:20 369 查看
class GBPolygon {
public:
    int _numVertices;
    std::vector<CCPoint> _verticesVec;
};

 点跟多边形的碰撞
static bool PointInPolygon(const CCPoint & p, 
const GBPolygon & polygon) 
{
int nCross =
0;
    int nCount = polygon._verticesVec.size();

for (int i =
0; i<nCount; i++) {
CCPoint p1 = polygon._verticesVec[i];
CCPoint p2 = polygon._verticesVec[(i+1)%nCount];
//
求解 y=p.y 与 p1p2 的交点
if(p1.y == p2.y)
continue; // p1p2 与 y=p0.y平行
if(p.y<(p1.y<p2.y?p1.y:p2.y))
continue;// 交点在p1p2延长线上
if(p.y>=(p1.y>p2.y?p1.y:p2.y))
continue;// 交点在p1p2延长线上
//
求交点的 X 坐标 --------------------------------------------------------------
float x = (p.y-p1.y)*(p2.x-p1.x)/(p2.y-p1.y)+p1.x;
if (x>p.x) {
nCross++;//
只统计单边交点
}
}
    // 单边交点为偶数,点在多边形之外 ---
return (nCross%2==1);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: