Unity - 在单独的线程上运行寻路算法

时间:2014-12-31 16:21:41

标签: c# unity3d path-finding coroutine

我在我的Unity 2D游戏中实现了A *寻路算法。一切正常,但在搜索广泛的地图时可能会引起恐慌。

问题是由主线程上执行的While循环引起的。我希望算法能够在一个单独的线程上运行,以便在函数运行时阻止游戏变弱。

我对协同程序的理解是它们更适合用于顺序函数,而不是像这样繁重的计算。该函数必须返回一个值或使用引用来附加值。

如何在不阻塞主线程的情况下实现这个CPU大量的计算?即多线程?

修改

Heisenbug指出,目前正在实施Coroutines。

来自"重计算功能的未完全提取"应该在多个框架中分散到均匀的工作负载。

//if the daemon is currently searching
public bool Searching;

//Create list for the algorithm
Pathfinding_Path Path = new Pathfinding_Path();
List<Pathfinding_Point> OpenList = new List<Pathfinding_Point>();
List<Pathfinding_Point> ClosedList = new List<Pathfinding_Point>();

//Agent is the object that shall pathfind, position is goal, callback
public IEnumerator Pathfind(GameObject Agent, Vector3 Position, Func<Pathfinding_Path,Vector3, bool,bool> Callback)
{
    //Abort if already searching
    if (Searching)
        yield break;

    Searching = true;

    //If the target position is not clear, abort
    if (!IsClear(Position))
    {
        Searching = false;
        yield break;
    }

    //Get the size of the agent
    Vector3 AgentSize = GetSize(Agent);

    //Start the algorithm
    Pathfinding_Point start = CreatePoint(AgentSize, Agent.transform.position, Position, 0);
    //Get possible steps from the first position
    CreateAdjacent(start, Position);
    //Add the node to the search tree
    OpenList.Add(start);

    //Keep track of how many iterations the function has ran (to not keep on going forever)
    int iterations = 0;

    //If there is an object to visit and the number of iterations is allowed
    while (OpenList.Count > 0 && iterations < 250)
    {
        iterations++;

        //Get the best node and visit it
        Pathfinding_Point point = GetBest(OpenList);
        OpenList.Remove(point);
        ClosedList.Add(point);    

        //Add all neighbors to the search tree
        foreach (Pathfinding_Point adjacent in point.Adjacent)
        {
            if (!ClosedList.Contains(adjacent))
            {
                if (!OpenList.Contains(adjacent))
                {
                    adjacent.Parent = point;


                    //The goal position is near, this is goal
                    if (Vector3.Distance(adjacent.Position, Position) <= AgentSize.sqrMagnitude * 0.5f)
                    {
                        //Add the final point to the path
                        Path.Add(adjacent);

                        //Get the last point
                        Pathfinding_Point step = Path.Points[0];
                        //Track backwards to find path
                        while(step.Parent != null){
                            Path.Add(step.Parent);
                            step = step.Parent;
                        }

                        Path.Finalize();

                        //Return the final path somehow (preferably using a callback method)
                        Callback(Path, Position, false);
                        Searching = false;
                        //Don't run the function no more
                        yield break;
                    } 
                    else if (IsClear(adjacent))
                    {
                        //Add to search tree
                        CreateAdjacent(adjacent, Position);
                        OpenList.Add(adjacent);
                    }
                }
                else
                {
                    //If the score is lower this way, re-calculate it
                    if (point.G + 1 < adjacent.G)
                    {
                        adjacent.G = point.G + 1;
                        adjacent.F = adjacent.G + adjacent.H;
                    }
                }
            }
        }
    }

    //If there are no more ways to go
    if(OpenList.Count == 0)
        yield break;

    //Here, the search has exceeded its limit on 250 iterations and shall continue after a small delay
    yield return new WaitForSeconds(0.005f);
    //The callback will run this function again, until the goal is reached or if there are no more nodes to visit
    Callback(Path, Position, true);
}

应该处理搜索功能可能达到的不同情况的回调

//Path to use if it succeded, position that was the initial target, if the search is not yet finished and should be continued
bool GetPath(Pathfinding_Path Path, Vector3 pz, bool Continue)
{
    //Run the function again with the same parameters as the first time
    if (Continue)
    {
        StartCoroutine(Pathfinder.Pathfind(gameObject, pz, GetPath));
    }
    else if (Path.Points.Count > 0)
    {
        //A path has been found
        InvestigatePath = Path;
    }

    return true;
}

2 个答案:

答案 0 :(得分:1)

你最终可以像往常一样在C#中使用threads。关键是这不是一个方便的解决方案,因为你需要保持你的线程与引擎循环同步。这可能不是一件容易的事。

  

我对协同程序的理解是它们更适合使用   顺序函数,不是像这样繁重的计算。

事实并非如此。协同程序的主要目标之一(它们只是iterator blocks)是随时间推移计算​​(多帧)以避免打嗝。它是一种合作多任务的形式,因此您可以获得几乎所有线程的好处,而不会出现同步的复杂性,因为脚本的主循环will be executed之后的协程Update已经完成

使用协同程序,您负责每帧执行多少计算,因此您可以自行组织代码以保持稳定的帧速率。在寻路的情况下可能是这样的:

IEnumerator PathFinding()
{
  while(!goalNodeReached)
  {
    VisitMaxNodes(maxNodesToVisit); // this function visit only a subset of the graph each frame
    yield return null;
  }
}

答案 1 :(得分:0)

你应该能够以惯用的方式生成一个新线程并执行你的计算,只要新线程不必与Unity本身交互,有很多方法可以实现,但很难说哪一个使用。我最后一次使用它时,Unity不支持某些.NET 4.0语言功能,例如“任务”,但这可能已经改变了。