为什么循环无止境?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了为什么循环无止境?相关的知识,希望对你有一定的参考价值。
大家好!我想换成UE4,现在想重复用航点找路的功能,在Unity中很好用,但在C++中出现了问题。
我想换成UE4,现在想重复用航点找路的功能,在Unity中很好用,但是在C ++中出现了问题,这个功能变成了无限循环,据我了解,openList不能变空,我的c ++知识还不足以解决这个问题。我将很高兴得到任何帮助
TArray<FVector> UWaypointsPathfinding::GetPath(UWaypoint* startNode, UWaypoint* goalNode)
UWaypoint* beginNode = startNode;
set<UWaypoint*> openList;
vector<UWaypoint*> closedList;
openList.insert(startNode);
startNode->previous = nullptr;
startNode->distance = 0;
while (!openList.empty())
startNode = *openList.begin();
openList.erase(openList.begin());
float dist = startNode->distance;
closedList.push_back(startNode);
if(startNode == goalNode) break;
int l = startNode->nearest.Num();
for (int i = 0; i < l; i++)
UWaypoint* node = startNode->nearest[i]->FindComponentByClass<UWaypoint>();
if(find(closedList.begin(),closedList.end(),node) != closedList.end() || openList.find(node) != openList.end())
continue;
node->previous = startNode;
node->distance = dist + FVector::Dist(node->GetOwner()->GetActorLocation(), startNode->GetOwner()->GetActorLocation());
node->distance += FVector::Dist(node->GetOwner()->GetActorLocation(), goalNode->GetOwner()->GetActorLocation());
openList.insert(startNode);
// create path...
return TArray<FVector>();
问题应该是在这块
if(startNode == goalNode) break;
int l = startNode->nearest.Num();
for (int i = 0; i < l; i++)
UWaypoint* node = startNode->nearest[i]->FindComponentByClass<UWaypoint>();
if(find(closedList.begin(),closedList.end(),node) != closedList.end() || openList.find(node) != openList.end())
continue;
node->previous = startNode;
node->distance = dist + FVector::Dist(node->GetOwner()->GetActorLocation(), startNode->GetOwner()->GetActorLocation());
node->distance += FVector::Dist(node->GetOwner()->GetActorLocation(), goalNode->GetOwner()->GetActorLocation());
openList.insert(startNode);
答案
逻辑很奇怪,所以这可能是打错了。你一开始就把startNode插入到openList中,然后在循环中擦掉它,再插入。所以openList永远只有一个成员startNode,所有的循环都是一样的。也许你的意思是 openList.insert(node);
而不是 openList.insert(startNode);
在循环的最后一行?
以上是关于为什么循环无止境?的主要内容,如果未能解决你的问题,请参考以下文章