行为树的构建

理解了您需要更详细的说明来析JSON并构建行为树。这里是一个加详细和具体步骤的解释,包括处理枚举映射和错误处理。

步骤1: 枚举和映射首先,为了简化从JSON中读取字符串并将它们转换为枚举值的过程,我们可以定义一些映射。假设您已经有了枚举EActionModeEConditionModecpp#include <map>#include <string>// 枚举到字符串的映射std::map<std::string, BT::EActionMode> actionModeMap = { {"Attack", BT::EActionMode::Attack}, {"Patrol", BT::EActionMode::Patrol}, {"Runaway", BT::EActionMode::Runaway}};std::map<std::string, BT::EConditionMode> conditionModeMap = { {"IsSeeEnemy", BT::EConditionMode::IsSeeEnemy}, {"IsHealthLow", BT::EConditionMode::IsHealthLow}, {"IsEnemyDead", BT::EConditionMode::IsEnemyDead}};std::map<std::string, BT::EPolicy> policyMap = { {"RequireAll", BT::EPolicy::RequireAll}, {"RequireOne", BT::EPolicy::RequireOne}};### 步骤2: 递归解析函数接着,我们定义一个递归函数来解析每个节点,并根据其类型调用BehaviorTreeBuilder的相应方法。这个函数会检查节点类型,并为节点的每个子节点递归调用自身。cppvoid parseNode(const json& node, BT::BehaviorTreeBuilder& builder) { std::string type = node["type"]; if (type == "Sequence") { builder.Sequence(); } else if (type == "Selector") { builder.Selector(); } else if (type == "ActiveSelector") { builder.ActiveSelector(); } else if (type == "Parallel") { builder.Parallel(policyMap[node["successPolicy"]], policyMap[node["failurePolicy"]]); } else if (type == "Action") { builder.Action(actionModeMap[node["actionMode"]]); } else if (type == "Condition") { builder.Condition(conditionModeMap[node["conditionMode"]], node["isNegation"]); } if (node.contains("children")) { for (const auto& child : node["children"]) { parseNode(child, builder); builder.Back(); } }}### 步骤3: 读取JSON并构建行为树最后,编写一个函数来读取JSON文件,初始化BehaviorTreeBuilder,并使用parseNode函数来填充它。cppBT::BehaviorTree* BuildBehaviorTreeFromJson(const std::string& filePath) { std::ifstream file(filePath); if (!file.is_open()) { std::cerr << "Failed to open file: " << filePath << std::endl; return nullptr; } json j; file >> j; BT::BehaviorTreeBuilder builder; parseNode(j, builder); return builder.End();}### 主函数调用在main函数中调用这个函数并处理返回的行为树对象。cppint main() { auto* tree = BuildBehaviorTreeFromJson("path/to/your/behavior_tree.json"); if (tree != nullptr) { // 使用行为树 // ... delete tree; } return 0;}这个过程提供了一个详细的视角,说明了如何从JSON文件中读取行为树的结构,并使用一个建造者模式动态构建行为树。请注意,根据你的项目具体情况,可能需要调整枚举类型和映射。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值