【COCOS2DX-BOX2D游戏开发之三】 读取tiledmap的tmx阻挡

来源:互联网 发布:国密算法sm2 java 编辑:程序博客网 时间:2024/05/16 05:01

做一款像素游戏项目,需要读取TMX文件中的阻挡区域,生成box2d的fixture,来做阻挡  使用cocos2dx版本: 2.2.2


1.在tmx文件中创建一个"Physics"的层,用来存放编辑器中生成的各种阻挡块

编辑器中主要有polygone, polyline,box和circle4种,其实box也属于polygone



2.我的tiled map 版本Version 0.9.1

查看tmx文件,增加的层属于<Objectgroup>是不会被渲染的,所以添加多个层对效率也没有什么影响, 我们此处叫"Physics"

上图的4个图形,分别对应下图XML的4个<object></object>


polyline读取一个初始点x,y,然后读取一些列相对于初始点的偏移值

box读取x,y,width,height

circle读取起始点x,y,外加直径width(height)足以,因为无法构造椭圆的b2Shape,所以我们构造圆

polygon读取起始点x,y,然后读取一些列相对于初始点的偏移值,类似于polyline




3.cocos2dx中解析此文件的时CCTMXXMLParser.cpp 大概在623行,但是代码中只解析了polygon,polyline和circle处解析代码为空,我们在此处添加完全


else if (elementName == "polygon")     {        // find parent object's dict and add polygon-points to it        ObjectGroup* objectGroup = (ObjectGroup*)m_pObjectGroups->lastObject();        CCDictionary* dict = (CCDictionary*)objectGroup->getObjects()->lastObject();        // get points value string        const char* value = valueForKey("points", attributeDict);        if(value)        {            CCArray* pPointsArray = new CCArray;            // parse points string into a space-separated set of points            stringstream pointsStream(value);            string pointPair;            while(std::getline(pointsStream, pointPair, ' '))            {                // parse each point combo into a comma-separated x,y point                stringstream pointStream(pointPair);                string xStr,yStr;                char buffer[32] = {0};                                CCDictionary* pPointDict = new CCDictionary;                // set x                if(std::getline(pointStream, xStr, ','))                {                    int x = atoi(xStr.c_str()) + (int)objectGroup->getPositionOffset().x;                    sprintf(buffer, "%d", x);                    CCString* pStr = new CCString(buffer);                    pStr->autorelease();                    pPointDict->setObject(pStr, "x");                }                // set y                if(std::getline(pointStream, yStr, ','))                {                    int y = atoi(yStr.c_str()) + (int)objectGroup->getPositionOffset().y;                    sprintf(buffer, "%d", y);                    CCString* pStr = new CCString(buffer);                    pStr->autorelease();                    pPointDict->setObject(pStr, "y");                }                                // add to points array                pPointsArray->addObject(pPointDict);                pPointDict->release();            }                        dict->setObject(pPointsArray, "points");            pPointsArray->release();                        dict->setObject(dict->objectForKey("points"), "polygonPoints");        }    }     else if (elementName == "polyline")    {        // find parent object's dict and add polyline-points to it        // ObjectGroup* objectGroup = (ObjectGroup*)m_pObjectGroups->lastObject();        // CCDictionary* dict = (CCDictionary*)objectGroup->getObjects()->lastObject();        // TODO: dict->setObject:[attributeDict objectForKey:@"points"] forKey:@"polylinePoints"];                // ------Added by Teng.start        // find parent object's dict and add polygon-points to it        ObjectGroup* objectGroup = (ObjectGroup*)m_pObjectGroups->lastObject();        CCDictionary* dict = (CCDictionary*)objectGroup->getObjects()->lastObject();                // get points value string        const char* value = valueForKey("points", attributeDict);        if(value)        {            CCArray* pPointsArray = new CCArray;                        // parse points string into a space-separated set of points            stringstream pointsStream(value);            string pointPair;            while(std::getline(pointsStream, pointPair, ' '))            {                // parse each point combo into a comma-separated x,y point                stringstream pointStream(pointPair);                string xStr,yStr;                char buffer[32] = {0};                                CCDictionary* pPointDict = new CCDictionary;                                // set x                if(std::getline(pointStream, xStr, ','))                {                    int x = atoi(xStr.c_str()) + (int)objectGroup->getPositionOffset().x;                    sprintf(buffer, "%d", x);                    CCString* pStr = new CCString(buffer);                    pStr->autorelease();                    pPointDict->setObject(pStr, "x");                }                                // set y                if(std::getline(pointStream, yStr, ','))                {                    int y = atoi(yStr.c_str()) + (int)objectGroup->getPositionOffset().y;                    sprintf(buffer, "%d", y);                    CCString* pStr = new CCString(buffer);                    pStr->autorelease();                    pPointDict->setObject(pStr, "y");                }                                // add to points array                pPointsArray->addObject(pPointDict);                pPointDict->release();            }                        dict->setObject(pPointsArray, "points");            pPointsArray->release();                        dict->setObject(dict->objectForKey("points"), "polylinePoints");        }                // ------Added by Teng.end    }    else if (elementName == "ellipse")    {        // ------Added by Teng.start        // Do nothing...        ObjectGroup* objectGroup = (ObjectGroup*)m_pObjectGroups->lastObject();        CCDictionary* dict = (CCDictionary*)objectGroup->getObjects()->lastObject();                CCObject *obj = new CCObject;        dict->setObject(obj, "ellipse");        obj->release();        // ------Added by Teng.end    }

4.剩下的就是我们在程序中获取出这些阻挡区域了

bool Map::createPhysical(b2World *world){    b2BodyDef body_def;    body_def.type = b2_staticBody;    body_def.position.SetZero();    mBody = world->CreateBody(&body_def);        // 找出阻挡区域所在的层    ObjectGroup* group = mTiledMap->objectGroupNamed("Physics");        CCArray* array = group->getObjects();    CCDictionary* dict;    CCObject* pObj = NULL;    CCARRAY_FOREACH(array, pObj)    {        dict = (CCDictionary*)pObj;        if (!dict)            continue;                b2FixtureDef fixture_def;                StaticBlockObject *sb_obj = new StaticBlockObject();                sb_obj->density = 1.0f;        sb_obj->friction = 0.2f;        sb_obj->restitution = 0.f;                // 读取所有形状的起始点        float x = ((CCString*)dict->objectForKey("x"))->floatValue();        float y = ((CCString*)dict->objectForKey("y"))->floatValue();                b2Shape* shape = NULL;                //多边形        CCObject *polygon = dict->objectForKey("polygonPoints");        if (polygon) {            CCArray *polygon_points = (CCArray*)polygon;                        std::vector<b2Vec2> points;                        // 必须将所有读取的定点逆向,因为翻转y之后,三角形定点的顺序已经逆序了,构造b2PolygonShape会crash            int c =polygon_points->count();            points.resize(c);            c--;                        CCDictionary* pt_dict;            CCObject* obj = NULL;            CCARRAY_FOREACH(polygon_points, obj)            {                pt_dict = (CCDictionary*)obj;                                if (!pt_dict) {                    continue;                }                                // 相对于起始点的偏移                float offx = ((CCString*)pt_dict->objectForKey("x"))->floatValue();                float offy = ((CCString*)pt_dict->objectForKey("y"))->floatValue();                                points[c--] = (b2Vec2((x + offx) / PTM_RATIO, (y-offy) / PTM_RATIO));            }                        b2PolygonShape *ps = new b2PolygonShape();            ps->Set(&points[0], points.size());            fixture_def.shape = ps;                        shape = ps;                        sb_obj->shape = StaticBlockObject::ST_POLYGON;        } else if (polygon = dict->objectForKey("polylinePoints")){            CCArray *polyline_points = (CCArray*)polygon;                        std::vector<b2Vec2> points;                        CCDictionary* pt_dict;            CCObject* obj = NULL;            CCARRAY_FOREACH(polyline_points, obj)            {                pt_dict = (CCDictionary*)obj;                                if (!pt_dict) {                    continue;                }                                float offx = ((CCString*)pt_dict->objectForKey("x"))->floatValue();                float offy = ((CCString*)pt_dict->objectForKey("y"))->floatValue();                points.push_back(b2Vec2((x + offx) / PTM_RATIO, (y-offy) / PTM_RATIO));            }                        b2ChainShape *ps = new b2ChainShape();            ps->CreateChain(&points[0], points.size());            fixture_def.shape = ps;                        shape = ps;                        sb_obj->shape = StaticBlockObject::ST_POLYGON;        } else if (dict->objectForKey("ellipse")) {            float width = ((CCString*)dict->objectForKey("width"))->floatValue();            float height = ((CCString*)dict->objectForKey("height"))->floatValue();                        b2CircleShape *ps = new b2CircleShape;            ps->m_p.Set((x+width/2) / PTM_RATIO, ((y+height/2)) / PTM_RATIO);            ps->m_radius = width/2/PTM_RATIO;            fixture_def.shape = ps;                        shape = ps;                        sb_obj->shape = StaticBlockObject::ST_CIRCLE;        } else {            float width = ((CCString*)dict->objectForKey("width"))->floatValue();            float height = ((CCString*)dict->objectForKey("height"))->floatValue();                        b2PolygonShape *ps = new b2PolygonShape;            ps->SetAsBox(width/2/PTM_RATIO, height/2/PTM_RATIO, b2Vec2((x+width/2)/PTM_RATIO, (y+height/2)/PTM_RATIO), 0);            fixture_def.shape = ps;                        shape = ps;                        sb_obj->shape = StaticBlockObject::ST_POLYGON;        }        fixture_def.density = sb_obj->density;        fixture_def.friction = sb_obj->friction;        fixture_def.restitution = sb_obj->restitution;        b2Fixture *fixture = mBody->CreateFixture(&fixture_def);        sb_obj->fixture = fixture;                if (shape) {            delete shape;            shape = NULL;        }                // Storage the Static block object.        mStaticBlockList.push_back(sb_obj);    }        return true;}


附带上StaticBlockObject代码,这个主要用来记录阻挡的类型、属性,以后用来做阻挡判断

/**    Storage fixture user data.    use for b2Fixture user data. */class iFixtureUserData{public:    typedef uint BodyType;    typedef uint FixtureType;        static const BodyType   BT_Avata = 0x000;  // no any use...    static const FixtureType FT_None = 0x000;        static const BodyType BT_Map  = 0x1000;    static const FixtureType FT_STATIC_OBJ = 0x1F01;    static const FixtureType FT_DYNAMIC_OBJ = 0x1F02;    //    static const BodyType BT_Role = 0x2000;    static const BodyType BT_Bullet = 0x2100;        static const FixtureType FT_BODY = 0x2F01;    static const FixtureType FT_FOOT = 0x2F02;    public:    iFixtureUserData(BodyType body_type, FixtureType fixture_type):        mBodyType(body_type), mFixtureType(fixture_type){    }        virtual ~iFixtureUserData() {            }    inline BodyType getBodyType() { return mBodyType; }    inline FixtureType getFixtureType() { return mFixtureType; }    protected:    BodyType mBodyType;    FixtureType mFixtureType;};/** Block object. specify a block area in physics engine. */class StaticBlockObject : public iFixtureUserData {public:    StaticBlockObject():    iFixtureUserData(BT_Map, FT_STATIC_OBJ),    fixture(NULL),    half_block(false)    {            }    enum ShapeType {        ST_POLYGON = 0,        ST_CIRCLE = 1,        ST_EDGE = 2    };        ShapeType shape;        // The shape type.        float density;    float friction;    float restitution;        b2Fixture *fixture;        bool half_block;};typedef std::vector<StaticBlockObject *> StaticBlockList;


因为是从代码中直接复制的,但无非实现了下面几个功能:

1.在map中找到"Physics"层

2.遍历读取所有图形的起始点,并分析是何种图形,并读取相应的属性

3.用读取的每个图形来构造b2Shape,用地图的body来构造b2Fixture

其中有几个地方需要注意:

1.因为Box2d和游戏中使用的单位不同,分别是米和像素,所以要用PTM_RATIO宏来转换

2.polygon读取的所有点来构造b2PolygonShape,这个序列必须是读取的所有点的反向列表,否则会报一个计算center断言错误

产生这个的原因是因为:tmx中的顶点坐标系是地图左上角,游戏中是左下角,CCTMXXMLParser.cpp中解析起始点的时候,自动帮我们转为游戏中的坐标

于是tmx中的1,2,3,4的顶点序列,构成的区域是凸多边形的内部,转换后就成为了4,3,2,1,构成的是凸多边形的外部

polyline因为不是闭合的,无所谓逆向一说

  std::vector<b2Vec2> points;                        // 必须将所有读取的定点逆向,因为翻转y之后,三角形定点的顺序已经逆序了,构造b2PolygonShape会crash            int c =polygon_points->count();            points.resize(c);            c--;                        CCDictionary* pt_dict;            CCObject* obj = NULL;            CCARRAY_FOREACH(polygon_points, obj)            {                pt_dict = (CCDictionary*)obj;                                if (!pt_dict) {                    continue;                }                                // 相对于起始点的偏移                float offx = ((CCString*)pt_dict->objectForKey("x"))->floatValue();                float offy = ((CCString*)pt_dict->objectForKey("y"))->floatValue();                                points[c--] = (b2Vec2((x + offx) / PTM_RATIO, (y-offy) / PTM_RATIO));            }                        b2PolygonShape *ps = new b2PolygonShape();            ps->Set(&points[0], points.size());            fixture_def.shape = ps;


5.传个效果图:



1 0