1. 程式人生 > >【COCOS2DX-BOX2D遊戲開發之三】 讀取tiledmap的tmx阻擋

【COCOS2DX-BOX2D遊戲開發之三】 讀取tiledmap的tmx阻擋

做一款畫素遊戲專案,需要讀取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.傳個效果圖: