Cocos2D-X:从TMX文件解析对象列表,将代码从版本2.X迁移到版本3.X

时间:2016-04-04 00:21:27

标签: c++ c++11 cocos2d-x

我是Cocos2D-X的新手,并且过去几个月一直在努力学习它。我正在尝试从书中创建一个示例游戏 Cocos2d-x游戏开发蓝图,在这个特定的章节中,它解释了如何使用平铺地图创建游戏。

我需要帮助解析TMX文件中的对象列表,我正在尝试将代码从版本2.X更新到版本3.X,因为我遇到了编译错误。我需要将已弃用的CCArray和CCDictionary更改为以下代码中的新cocos :: Vector和Map

void GameWorld::CreateTiledMap()
{
// generate level filename
char buf[128] = {0};
sprintf(buf, "level_%02d.tmx", GameGlobals::level_number_);
// create & add the tiled map
tiled_map_ = CCTMXTiledMap::create(buf);
addChild(tiled_map_);

// get the size of the tiled map
columns_ = (int)tiled_map_->getMapSize().width;
rows_ = (int)tiled_map_->getMapSize().height;

// save a reference to the layer containing all the bricks
bricks_layer_ = tiled_map_->layerNamed("Bricks");

// parse the list of objects
CCTMXObjectGroup* object_group = tiled_map_->objectGroupNamed("Objects");
CCArray* objects = object_group->getObjects();
int num_objects = objects->count();

for(int i = 0; i < num_objects; ++i)
{
    CCDictionary* object = (CCDictionary*)(objects->objectAtIndex(i));

    // create the Hero at this spawning point
    if(strcmp(object->valueForKey("name")->getCString(), "HeroSpawnPoint") == 0)
    {
        CreateHero(ccp(object->valueForKey("x")->floatValue(), object->valueForKey("y")->floatValue()));
    }
    // create an Enemy at this spawning point
    else if(strcmp(object->valueForKey("name")->getCString(), "EnemySpawnPoint") == 0)
    {
        CCPoint position = ccp(object->valueForKey("x")->floatValue(), object->valueForKey("y")->floatValue());
        CCPoint speed = ccp(object->valueForKey("speed_x")->floatValue(), object->valueForKey("speed_y")->floatValue());
        CreateEnemy(position, speed);
    }
    // create a Platform at this spawning point
    else if(strcmp(object->valueForKey("name")->getCString(), "PlatformSpawnPoint") == 0)
    {
        CCPoint position = ccp(object->valueForKey("x")->floatValue(), object->valueForKey("y")->floatValue());
        CCPoint speed = ccp(object->valueForKey("speed_x")->floatValue(), object->valueForKey("speed_y")->floatValue());
        CreatePlatform(position, speed);
    }
    // save the point where the level should complete
    else if(strcmp(object->valueForKey("name")->getCString(), "LevelCompletePoint") == 0)
    {
        level_complete_height_ = object->valueForKey("y")->floatValue();
    }
}
}

我自己尝试过转换它,但都没有成功。 我无法将CCArray转换为cocos :: Vector, 但主要是将CCDictionary改为cocos :: Map。有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

Cocos2d-x有很多测试,非常有用。来自\tests\cpp-tests\Classes\TileMapTest\TileMapTest.cpp

auto map = TMXTiledMap::create("TileMaps/test-object-layer.tmx");
addChild(map, -1, kTagTileMap);

CCLOG("----> Iterating over all the group objets");

auto group = map->getObjectGroup("Objects");
auto& objects = group->getObjects();
for (auto& obj : objects)
{
    ValueMap& dict = obj.asValueMap();

    float x = dict["x"].asFloat();
    string name = dict["name"].asString();
}