Advertisement
teleias

Dijkstra's C# Unity3D

Dec 9th, 2013
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 4.96 KB | None | 0 0
  1. //Here's a bit of Unity3D code on how to make/use Dijkstra's Algorithm.
  2.  
  3. using UnityEngine;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6.  
  7. [RequireComponent(typeof(LineRenderer))]
  8.  
  9. public class Dijkstra : Pathfinding{
  10.     protected override void Start()
  11.     {
  12.         SetUpDirections();
  13.     }
  14.     public override List<Node> Begin (Node[,] _fullGrid, Node _startNode, Node _endNode) {
  15.         Display (); //Resets all the colors on the tiles.
  16.         sx = _fullGrid.GetLength(0);
  17.         sz = _fullGrid.GetLength(1);
  18.         openList.Clear();
  19.         unopenList.Clear();
  20.         fullGrid = _fullGrid;
  21.         startNode = _startNode;
  22.         endNode = _endNode;
  23.         BeginCalculation();
  24.         return openList;
  25.     }
  26.     private List<Node> unopenList = new List<Node>();
  27.  
  28.     protected override void SetUpDirections()
  29.     {
  30.         directions.Add(new V2(-1,  0));
  31.         directions.Add(new V2( 0, -1));
  32.         directions.Add(new V2( 0,  1));
  33.         directions.Add(new V2( 1,  0));
  34.     }
  35.    
  36.     /// <summary>
  37.     /// Sets up information so Dijkstra's can begin.
  38.     /// </summary>
  39.     /// <param name='v2'>
  40.     /// A Vector2. The place to begin Dijkstra's from.
  41.     /// </param>
  42.     protected override void BeginCalculation()
  43.     {
  44.         //This check ensures that we don't allow the algorithm
  45.         // to be running more than once at the same time.
  46.  
  47.         finished = false;
  48.         //Reset all the values in the fullGrid.
  49.         // Their distances all are at the max value, so any value
  50.         // Dijkstra's finds will replace the current info.
  51.         foreach(Node n in fullGrid)
  52.         {
  53.             n.distance = int.MaxValue;
  54.             n.parent = null;
  55.             unopenList.Add(n);
  56.         }
  57.         maxDistance = 1;
  58.         StartCoroutine(Calculate(startNode.v2, 0));
  59.         distance = endNode.distance;
  60.     }
  61.     protected override IEnumerator Calculate(V2 v2, int d)
  62.     {
  63.         Node v2Node = fullGrid[v2.x,v2.z];
  64.         v2Node.distance = 0;
  65.         do
  66.         {
  67.             Node smallestDistanceNode = null;
  68.             unopenList.Sort(compareByDistance);
  69.             smallestDistanceNode = unopenList[unopenList.Count-1];
  70.             if(smallestDistanceNode.distance == int.MaxValue)
  71.             {
  72.                 break; 
  73.             }
  74.             Node n = smallestDistanceNode;
  75.             unopenList.Remove(n);
  76.            
  77.             yield return StartCoroutine(UpdateCell(n));
  78.            
  79.             if(!openList.Contains(n))
  80.                 openList.Add(n);
  81.             //For every node adjacent to the node we're looking at.
  82.             foreach(V2 adj in getAdjacents(n.v2))
  83.             {
  84.                 Node adjNode = fullGrid[adj.x, adj.z];
  85.                 if(adjNode.distance > n.distance+adjNode.weight)
  86.                 {
  87.                     //Here's the path update.
  88.                     adjNode.distance = n.distance+adjNode.weight;
  89.                     adjNode.parent = n;
  90.                 }
  91.             }
  92.             //if(unopenList.Count > 0)
  93.             //  if(unopenList[unopenList.Count-1].distance > endNode.distance)
  94.             //      break; 
  95.         }while(unopenList.Count != 0);
  96.         Display();
  97.         openList.Sort(compareByDistance);
  98.         yield return StartCoroutine(FindPathBack(startNode, endNode));
  99.         distance = endNode.distance;
  100.         startNode = endNode = null;
  101.         finished = true;
  102.         yield return null;
  103.     }
  104.     public List<Node> pathBack;
  105.     protected override IEnumerator FindPathBack(Node start, Node end)
  106.     {
  107.         pathBack = new List<Node>();
  108.         Node n = end;
  109.         do
  110.         {
  111.             pathBack.Add(n);
  112.             yield return StartCoroutine(UpdateCell(n, Color.red, Color.magenta));
  113.             n = n.parent;
  114.         }while(n != null);
  115.     }
  116.     protected int compareByDistance(Node b, Node a)
  117.     {
  118.         int result = (a.distance).CompareTo(b.distance);
  119.         return result;
  120.     }
  121.     protected override IEnumerator UpdateCell(Node n)
  122.     {
  123.         yield return StartCoroutine(UpdateCell(n, Color.blue, Color.green));   
  124.     }
  125.     protected IEnumerator UpdateCell(Node n, Color c1, Color c2)
  126.     {
  127.         //Updates the cell/node's text to show the [distance] variable.
  128.         string s = n.distance+"";
  129.         if(n.distance/100f >= 1)
  130.             s = "";
  131.         if(maxDistance < n.distance && n.distance <= .9f*int.MaxValue)
  132.         {
  133.             maxDistance = n.distance;
  134.             UpdateAllCells();
  135.         }
  136.         //n.cell.GetComponentInChildren<TextMesh>().text = s;
  137.         n.cell.renderer.material.color = Color.Lerp(c1, Color.Lerp(c2, Color.black, .5f),
  138.             (float)(n.distance/(float)maxDistance));
  139.         yield return new WaitForSeconds(0.001f);
  140.     }
  141.     protected override void UpdateAllCells()
  142.     {  
  143.         foreach(Node n in openList)
  144.         {
  145.             n.cell.renderer.material.color = Color.Lerp(Color.blue, Color.Lerp(Color.green, Color.black, .5f),
  146.             (float)(n.distance/(float)maxDistance));
  147.         }
  148.     }
  149.     List<V2> directions = new List<V2>();
  150.     protected override List<V2> getAdjacents(V2 v2)
  151.     {
  152.         //Gets all nodes around the node with position [v2].
  153.         List<V2> result = new List<V2>();
  154.         foreach(V2 dir in directions)
  155.         {
  156.             int x = v2.x+dir.x;
  157.             int z = v2.z+dir.z;
  158.             //If it's one of these, it's invalid. Like position (-1,0) is not on the grid.
  159.             if( x < 0   ||
  160.                 x>=sx   ||
  161.                 z < 0   ||
  162.                 z >=sz)
  163.             {
  164.                
  165.             }
  166.             else
  167.             {
  168.                 result.Add(new V2(x,z));   
  169.             }
  170.         }
  171.         return result;
  172.     }
  173.     protected override void Display()
  174.     {
  175.         for(int ix = 0; ix < sx; ix++)
  176.         {
  177.             for(int iz = 0; iz < sz; iz++)
  178.             {
  179.                 Node m = fullGrid[ix, iz];
  180.                 if(m != null)
  181.                 {
  182.                     m.cell.renderer.material.color = Color.Lerp(Color.black, Color.grey, m.distance/10f);
  183.                 }
  184.             }
  185.         }
  186.     }
  187. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement