Cocos2d-x 3.x 生成和加载plist文件

本文详细介绍了在Cocos2d-x 3.x中如何创建和读取plist文件。通过示例说明了如何在游戏开发中保存和还原炮塔坐标,实现游戏状态持久化。内容涵盖输出炮塔位置到plist文件的函数实现,以及读取文件并恢复游戏布局的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、创建plist文件

在学习《Cocos2d-x 3.x游戏开发之旅》时,点击完屏幕以创建很多炮塔的(x, y)坐标,使用ValueMap把炮塔坐标写入plist文件,保存当前玩家创建的炮塔,以便再次进入游戏时还原之前的炮塔(根据坐标)。下面是创建plist文件的函数:

void TowerPosEditorScene::outputPosToPlistFile()
{
    String* s_pFilePath = String::createWithFormat("tollgate/towerPos_level_%d.plist", m_iCurLevel);
    outputPosToPlistFile(m_towerPosList, s_pFilePath->getCString());
}

// 输出plist文件————炮台坐标
void TowerPosEditorScene::outputPosToPlistFile(Vector<PosBase*> coll, const char* sFilePath)
{
    ValueMap fileDataMap;
    int index = 1;// 这里从1开始

    for (auto posBase : coll)
    {
        ValueMap data; // typedef unordered_map<std::string key, Value value> ValueMap;
        data["x"] = posBase->getPos().x; // data[key] = value;
        data["y"] = posBase->getPos().y; // 注意:fileDataMap为key,data为value
        fileDataMap[StringUtils::toString(index)] = Value(data);// fileDataMap[key] = value
        index++;
    }
    // Write a ValueMap into a plist file.
    FileUtils::getInstance()->writeToFile(fileDataMap, sFilePath);
}

在outputPosToPlistFile()函数中,首先使用cocos2d::String类创建保存plist文件的”完整路径s_pFilePath变量“,然后把该变量传入重载的outputPosToPlistFile函数。注意:这里创建文件的方式有点小特别:根据游戏当前等级来命名要创建的plist文件,这样做的好处是,不同等级(或关卡)都会有一份plist文件。

m_towerPosList变量为在在TowerPosEditorScene中声明,用于存储炮塔坐标,PosBase为TowerPos的基类。


二、读取plist文件

玩家创建好炮塔后,点击“输出到文件”后,所有创建的炮塔坐标都存在了plist文件中,那么怎么读取(遍历)plist文件中的炮塔坐标,并把炮塔还原到屏幕呢?作者是这么处理的:

/// 加载坐标对象
Vector<PosBase*> PosLoadUtil::loadPosWithFile(const char* sFilePath, Node* container, int iLevel, bool isDebug)
{
    Vector<PosBase*> posList;
    ValueMap fileDataMap = FileUtils::getInstance()->getValueMapFromFile(sFilePath);
    int size = fileDataMap.size();
    for (int i = 1; i <= size; i++)// 注意i从1开始并<=size
    {
        Value value = fileDataMap[StringUtils::toString(i)];

        ValueMap data = value.asValueMap();

        PosBase* posBase = TowerPos::create(Point(data["x"].asInt(), data["y"].asInt()), isDebug);
        posList.pushBack(posBase);

        if (container != NULL)
        {
            container->addChild(posBase, iLevel);
        }
    }
    return posList;
}

参考:Cocos2d-x 3.x游戏开发之旅 钟迪龙 著

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值