首页 > 其他 > 详细

【cocos2dx游戏开发box2d】之 三 读取tiledmap的tmx阻挡

时间:2014-03-21 16:28:35      阅读:554      评论:0      收藏:0      [点我收藏+]

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


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

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


bubuko.com,布布扣

2.我的tiled map 版本Version 0.9.1

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

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

bubuko.com,布布扣

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

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

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.传个效果图:

bubuko.com,布布扣


【cocos2dx游戏开发box2d】之 三 读取tiledmap的tmx阻挡,布布扣,bubuko.com

【cocos2dx游戏开发box2d】之 三 读取tiledmap的tmx阻挡

原文:http://blog.csdn.net/teng_ontheway/article/details/21704279

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!