点跟多边形的碰撞检测

来源:互联网 发布:双色球红球最简单算法 编辑:程序博客网 时间:2024/05/01 07:45


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);

}

0 0
原创粉丝点击