[分享]不用Box2d/Chipchunk的像素级Armature碰撞检测

希望对大家有用。


//http://blog.csdn.net/hjh2005/article/details/9246967
static bool pointInPolygon(const std::vector<Point> &vertices, const cocos2d::Point &p) {
    int polySides = vertices.size();
    float x = p.x, y = p.y;
    int   i,j=polySides-1 ;
    bool  oddNodes= false     ;

    for (i=0;i<polySides; i++) {
        auto vi = vertices*, vj = vertices;
        if((vi.y < y && vj.y>=y || vj.y<y && vi.y>=y) && (vi.x<=x || vj.x<=x)) {
            oddNodes^=(vi.x+(y-vi.y)/(vj.y-vi.y)*(vj.x-vi.x)<x);
        }
        j=i;
    }

    return oddNodes; 
}

//判断某个点是否在Armature内,比如touch event
bool JSWrapper::hitArmature(cocostudio::Armature *armature, const cocos2d::Point &worldPoint) {
    if( !armature || !armature->getParent() )
        return false;

    const Map<std::string, cocostudio::Bone*>& map = armature->getBoneDic();
    Point localPoint = armature->getParent()->convertToNodeSpace(worldPoint);
    for(const auto& element : map) {
        cocostudio::Bone *bone = element.second;
        cocostudio::ColliderDetector *detector = bone->getColliderDetector();

        if (!detector)
            continue;
        
        const cocos2d::Vector<cocostudio::ColliderBody*>& bodyList = detector->getColliderBodyList();
        if( bodyList.size() == 0 )
            continue;

        //Point localPoint = bone->convertToNodeSpace(worldPoint);                
        for (const auto& object : bodyList)
        {
            cocostudio::ColliderBody *body = static_cast<cocostudio::ColliderBody*>(object);
            const std::vector<Point> &vertexList = body->getCalculatedVertexList();
            if( pointInPolygon(vertexList, localPoint) )
                return true;
        }
    }

    return false;
}
*

赞一个, 感谢楼主无私奉献

求楼主发布个调用实例~

同求,最好能有个具体实例~

把touchEvent的坐标点传入就可以了


XXX::onTouchBegan(Touch *touch, Event *unusedEvent) {
        if( hitArmature(yourArmature, touch->getLocation()) ) {
        ...
    }
}

能不能来个用box2d版的碰撞写法

顶楼主一个。。。第九行的应该是auto vi = vertices吧。。

赞啊,那么判断矩形和多边形相交有没有类似的方法?

问楼主个问题,30行 if (!detector)
总是返回NULL是什么问题啊。。有什么东西没开启吗?

— Begin quote from ____

引用第7楼cppworker于2014-07-16 10:38发表的 :
赞啊,那么判断矩形和多边形相交有没有类似的方法? http://www.cocoachina.com/bbs/job.php?action=topost&tid=196729&pid=1004559

— End quote

多边形和多边形相交的问题
可以参考裁剪算法Weiler-Atherton
github上有个c#版本可以参考

test* test

i ]无法显示出来呀


请问,在Lua下,如何让armature处理点击事件?