为什么循环无止境?

问题描述 投票:0回答:1

大家好!我想换成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);
}
c++ unreal-engine4
1个回答
0
投票

逻辑很奇怪,所以这可能是打错了。你一开始就把startNode插入到openList中,然后在循环中擦掉它,再插入。所以openList永远只有一个成员startNode,所有的循环都是一样的。也许你的意思是 openList.insert(node); 而不是 openList.insert(startNode); 在循环的最后一行?

© www.soinside.com 2019 - 2024. All rights reserved.