RUBehaviacTree.cpp 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #include "RUBehaviacTree.h"
  2. #include "RUBehaviacTreeManger.h"
  3. NS_RU_BEGIN
  4. RUBehaviacTree::RUBehaviacTree()
  5. {
  6. }
  7. RUBehaviacTree::~RUBehaviacTree()
  8. {
  9. }
  10. bool RUBehaviacTree::loadBt(const std::string& btName)
  11. {
  12. std::string btFile = btName.substr(0, btName.find(".xml"));
  13. bool isOk = btload(btFile.c_str());
  14. CCASSERT(isOk, "加载行为树失败");
  15. if(isOk) {
  16. btsetcurrent(btFile.c_str());
  17. }
  18. return isOk;
  19. }
  20. void RUBehaviacTree::setData(const std::map<std::string, std::string>& stringMap)
  21. {
  22. }
  23. void RUBehaviacTree::runBehaviacTree(){
  24. runBehaviacTree({},nullptr,false);
  25. }
  26. void RUBehaviacTree::runBehaviacTree(const std::map<std::string, std::string>& stringMap, std::function<void(bool isSuccess)> treeRunEndCb, bool removeSelf){
  27. _isRunning = true;
  28. _removeSelf = removeSelf;
  29. setData(stringMap);
  30. _treeRunEndCb = treeRunEndCb;
  31. RUBehaviacTreeManger::getInstance()->_addBehaviacTree(this);
  32. _update();
  33. }
  34. void RUBehaviacTree::_update(){
  35. if(_isRunning){
  36. behaviac::EBTStatus status = btexec();
  37. if(status != behaviac::EBTStatus::BT_RUNNING){
  38. _isRunning = false;
  39. RUBehaviacTreeManger::getInstance()->_removeBehaviacTree(this);
  40. if (_treeRunEndCb != nullptr) {
  41. ///因为同一个物件连续执行多个事件时,runBehaviacTree函数中会把_treeRunEndCb覆盖,导致地址错误。
  42. std::function<void(bool isSuccess)> tTreeRunEndCb = _treeRunEndCb;
  43. _treeRunEndCb = nullptr;
  44. tTreeRunEndCb(status == behaviac::EBTStatus::BT_SUCCESS);
  45. }
  46. if (_removeSelf) {
  47. behaviac::Agent::Destroy(this);
  48. }
  49. }
  50. }
  51. }
  52. behaviac::EBTStatus RUBehaviacTree::_runIntervalAction(const std::string& actKey, const std::function<void(std::function<void(bool isSuccess)>)>& actFunc)
  53. {
  54. if (actKey != _actKey) {
  55. _actKey = actKey;
  56. _actStatus = behaviac::EBTStatus::BT_INVALID;
  57. }
  58. behaviac::EBTStatus status = _actStatus;
  59. if (status == behaviac::EBTStatus::BT_INVALID) {
  60. _actStatus = behaviac::EBTStatus::BT_RUNNING;
  61. status = _actStatus;
  62. if(actFunc) {
  63. actFunc([=](bool isSuccess){
  64. if(isSuccess) {
  65. _actStatus = behaviac::EBTStatus::BT_SUCCESS;
  66. } else {
  67. _actStatus = behaviac::EBTStatus::BT_FAILURE;
  68. }
  69. });
  70. }
  71. }else if(status == behaviac::EBTStatus::BT_SUCCESS || status == behaviac::EBTStatus::BT_FAILURE){
  72. _actStatus = behaviac::EBTStatus::BT_INVALID;
  73. _actKey = "";
  74. }
  75. return status;
  76. }
  77. bool RUBehaviacTree::isRunning()
  78. {
  79. return _isRunning;
  80. }
  81. NS_RU_END