Guest User

Untitled

a guest
Feb 19th, 2017
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 14.08 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections.Generic;
  3. using System;
  4.  
  5. public class AStar : MonoBehaviour
  6. {
  7.     // The starting point of our algorithm.
  8.     [SerializeField]
  9.     public NodeScript start;
  10.  
  11.     // The goal of our algorithm.
  12.     [SerializeField]
  13.     public NodeScript goal;
  14.  
  15.     // The current point of our algorithm.
  16.     [SerializeField]
  17.     public NodeScript current;
  18.  
  19.     // The open list.
  20.     HashSet<NodeScript> openList = new HashSet<NodeScript>();
  21.  
  22.     // The closed list.
  23.     HashSet<NodeScript> closedList = new HashSet<NodeScript>();
  24.  
  25.     // The finalPath.
  26.     Stack<NodeScript> finalPath = new Stack<NodeScript>();
  27.  
  28.     // Reference to our Node Creator, the gameobject that instaniates all the nodes.
  29.     NodeCreator boardSize;
  30.  
  31.     // The monster
  32.     [SerializeField]
  33.     private GameObject zombie;
  34.  
  35.     // The player
  36.     [SerializeField]
  37.     private PlayerController player;
  38.  
  39.     // Determines which nodescore this monster is going to use for his calculations.
  40.     private int nodeScoresNumber = 0;
  41.  
  42.     // The next node the zombie needs to walk to.
  43.     public NodeScript nextNode;
  44.  
  45.     // Is set to true if AStar has run atleast once.
  46.     public bool isRunning;
  47.  
  48.     // If this is true, AStar will run.
  49.     public bool activateAStar;
  50.  
  51.     private void Start()
  52.     {
  53.         activateAStar = true;
  54.         isRunning = false;
  55.         nextNode = null;
  56.         boardSize = GameObject.Find("NodeCreator").GetComponent<NodeCreator>();
  57.         player = GameObject.Find("Character").GetComponent<PlayerController>();
  58.     }
  59.  
  60.     //tmp values
  61.     float a = .5f;
  62.     float b = .5f;
  63.  
  64.     private void Update()
  65.     {
  66.        
  67.         if (Input.GetKeyDown("z") && Time.time > a)
  68.         {
  69.             a = b + Time.time;
  70.             SetStartNode();
  71.         }
  72.         if (Input.GetKeyDown("x") && Time.time > a)
  73.         {
  74.             a = b + Time.time;
  75.             SetGoalNode();
  76.         }
  77.         if (Input.GetKeyDown("c") && Time.time > a)
  78.         {
  79.             a = b + Time.time;
  80.             FindPath();
  81.         }
  82.         if (Input.GetKeyDown("v") && Time.time > a)
  83.         {
  84.             a = b + Time.time;
  85.             FindFinalPath();
  86.         }
  87.         if (Input.GetKeyDown("b") && Time.time > a)
  88.         {
  89.             a = b + Time.time;
  90.             ResetStuff();
  91.         }
  92.         if (Input.GetKeyDown("n"))
  93.         {
  94.             a = b + Time.time;
  95.             //
  96.         }
  97.         RunAStar();
  98.     }
  99.  
  100.     // Finds our start and current node.
  101.     private void SetStartNode()
  102.     {
  103.         RaycastHit2D hit = Physics2D.Raycast(zombie.transform.position, Vector2.zero);
  104.  
  105.         if(hit)
  106.         {
  107.             start = hit.collider.gameObject.GetComponent<NodeScript>();
  108.            
  109.             current = hit.collider.gameObject.GetComponent<NodeScript>();
  110.  
  111.             openList.Add(current);
  112.             if (start == null)
  113.             {
  114.                 Debug.Log("Start = null");
  115.             }
  116.             else
  117.             {
  118.                 Debug.Log("Start = set");
  119.             }
  120.         } else
  121.         {
  122.             Debug.Log("Raycast didn't hit.");
  123.         }
  124.     }
  125.  
  126.     // Finds our goal node. (the player)
  127.     private void SetGoalNode()
  128.     {
  129.         RaycastHit2D hit = Physics2D.Raycast(player.transform.position, Vector2.zero);
  130.  
  131.         if (hit)
  132.         {
  133.             goal = hit.collider.GetComponent<NodeScript>();
  134.         }
  135.         else
  136.         {
  137.             Debug.Log("Raycast didn't hit.");
  138.         }
  139.     }
  140.  
  141.     // Finds the path from the start to the goal.
  142.     private void FindPath()
  143.     {
  144.         while (current != goal)
  145.         {
  146.             FindNewCurrentNode();
  147.  
  148.             openList.Remove(current);
  149.             closedList.Add(current);
  150.             finalPath.Push(current);
  151.  
  152.             //SpriteRenderer currentSprite = current.GetComponent<SpriteRenderer>();
  153.             //currentSprite.color = Color.cyan;
  154.  
  155.             // The two for loops make a 3x3 grid around the current node, where the current node is the middle.
  156.             for (int x = -1; x <= 1; x++)
  157.             {
  158.                 for (int y = -1; y <= 1; y++)
  159.                 {
  160.                     Point neighbourPos = new Point(current.gridPosition.X - x, current.gridPosition.Y - y);
  161.  
  162.                     // If the Point of the neighbour is not the same as the Point of the current node && the position(point x,y) of the neighbour is on the board
  163.                     if (neighbourPos != current.gridPosition && InBounds(neighbourPos))
  164.                     {
  165.  
  166.                         // Uses the Point key to get the corresponding node out of the nodesList.
  167.                         NodeScript neighbour = NodeCreator.nodesList[neighbourPos];
  168.  
  169.                         // If the closed list doesn't contain the neighbour && the neighbour is walkable.
  170.                         if (!closedList.Contains(neighbour) && neighbour.isWalkable)
  171.                         {
  172.                             int gCost = 0;
  173.  
  174.                             //Calculates the G cost.
  175.                             if (Math.Abs(x - y) == 1)
  176.                             {
  177.                                 neighbour.G = 10;
  178.                                 gCost = 10;
  179.                             }
  180.                             else
  181.                             {
  182.                                 if(!DiagonalMoveCheck(current, neighbour))
  183.                                 {
  184.                                     continue;
  185.                                 }
  186.                                 neighbour.G = 14;
  187.                                 gCost = 14;
  188.                             }
  189.  
  190.                             // Calculates the H cost.
  191.                             int hCost = GetDistance(neighbour, goal);
  192.  
  193.                             // Calculates the F cost.
  194.                             int fCost = gCost + hCost;
  195.  
  196.                             // If the neighbour's previous fScore is zero || the neighbour isn't in the open list.
  197.                             if(neighbour.F == 0 || !openList.Contains(neighbour))
  198.                             {
  199.                                 neighbour.parent = current;
  200.  
  201.                                 neighbour.G = gCost;
  202.  
  203.                                 neighbour.H = hCost;
  204.  
  205.                                 neighbour.F = fCost;
  206.  
  207.                             // If the neighbour's previous fScore is greater then the new fScore && the neighbour isn't in the open list.
  208.                             } else if(neighbour.F > fCost || !openList.Contains(neighbour))
  209.                             {
  210.                                 neighbour.parent = current;
  211.  
  212.                                 neighbour.G = gCost;
  213.  
  214.                                 neighbour.H = hCost;
  215.  
  216.                                 neighbour.F = fCost;
  217.                             }
  218.  
  219.                             if (!openList.Contains(neighbour))
  220.                             {
  221.                                 openList.Add(neighbour);
  222.                             }
  223.                         }
  224.                     }
  225.                 }
  226.             }
  227.         }
  228.         if (current == goal)
  229.         {
  230.             Debug.Log("Path has been found");
  231.         }
  232.     }
  233.    
  234.     // Returns true if the position is on the board.
  235.     public bool InBounds(Point position)
  236.     {
  237.         return position.X >= 0 && position.Y >= 0 && position.X <= boardSize.x - 1 && position.Y <= boardSize.y - 1;
  238.     }
  239.  
  240.     // Calculates the distance between the neighbour node and the goal node.
  241.     private int GetDistance(NodeScript neighbour, NodeScript goal)
  242.     {
  243.         int dstX = Mathf.Abs(neighbour.gridPosition.X - goal.gridPosition.X);
  244.         int dstY = Mathf.Abs(neighbour.gridPosition.Y - goal.gridPosition.Y);
  245.  
  246.         if(dstX > dstY)
  247.         {
  248.             return (14 * dstY) + 10 * (dstX - dstY);
  249.         }
  250.         return (14 * dstX) + 10 * (dstY - dstX);
  251.     }
  252.  
  253.     // Finds a new current node based on the neighbours lowest F score.
  254.     private void FindNewCurrentNode()
  255.     {
  256.         int fScore = 10000;
  257.         Point point;
  258.         if(current != null && openList.Count > 1) //openList.Count > 1
  259.         {
  260.             foreach (NodeScript nodes in openList)
  261.             {
  262.                 if (fScore > nodes.F) // Dit gedeelte geeft de error.
  263.                 {
  264.  
  265.                     fScore = nodes.F;
  266.                     point = nodes.gridPosition;
  267.  
  268.                     // DEZE 2 regels zou Ik EIGENLIJK ui tde foreach moeten halen.
  269.                     // En dan moet ik iets met ref/out doen, omdat de point word niet geupdate buiten de if statement (by reference/by value).
  270.                     // Dit zal wss een performance boost geven.
  271.                     NodeScript newCurrent = NodeCreator.nodesList[point];
  272.                     current = newCurrent;
  273.                 }
  274.             }
  275.         }
  276.     }
  277.  
  278.     // Returns true if the diagonal move is possible, so there aren't any obstacles blocking the path. (Otherwise we could walk over a wall.)
  279.     private bool DiagonalMoveCheck(NodeScript current, NodeScript neighbour)
  280.     {
  281.         Point neighbourPoint1;
  282.         Point neighbourPoint2;
  283.  
  284.         // If the neighbour is down-right of the current.
  285.         if(current.gridPosition.X < neighbour.gridPosition.X && current.gridPosition.Y > neighbour.gridPosition.Y)
  286.         {
  287.             // Neighbour right of the current.
  288.             neighbourPoint1 = new Point(current.gridPosition.X + 1, current.gridPosition.Y);
  289.             // Neighbour under of the current.
  290.             neighbourPoint2 = new Point(current.gridPosition.X, current.gridPosition.Y - 1); ;
  291.  
  292.             // If both neighbours are on the board and both are walkable.
  293.             if(InBounds(neighbourPoint1) && InBounds(neighbourPoint2) && NodeCreator.nodesList[neighbourPoint1].isWalkable && NodeCreator.nodesList[neighbourPoint2].isWalkable)
  294.             {
  295.                 return true;
  296.             }
  297.         }
  298.         // If the neighbour is down-left of the current.
  299.         if (current.gridPosition.X > neighbour.gridPosition.X && current.gridPosition.Y > neighbour.gridPosition.Y)
  300.         {
  301.             // Neighbour left of the current.
  302.             neighbourPoint1 = new Point(current.gridPosition.X - 1, current.gridPosition.Y);
  303.             // Neighbour under of the current.
  304.             neighbourPoint2 = new Point(current.gridPosition.X, current.gridPosition.Y - 1); ;
  305.  
  306.             // If both neighbours are on the board and both are walkable.
  307.             if (InBounds(neighbourPoint1) && InBounds(neighbourPoint2) && NodeCreator.nodesList[neighbourPoint1].isWalkable && NodeCreator.nodesList[neighbourPoint2].isWalkable)
  308.             {
  309.                 return true;
  310.             }
  311.         }
  312.         // If the neighbour is up-right of the current.
  313.         if (current.gridPosition.X < neighbour.gridPosition.X && current.gridPosition.Y < neighbour.gridPosition.Y)
  314.         {
  315.             // Neighbour right of the current.
  316.             neighbourPoint1 = new Point(current.gridPosition.X + 1, current.gridPosition.Y);
  317.             // Neighbour above of the current.
  318.             neighbourPoint2 = new Point(current.gridPosition.X, current.gridPosition.Y + 1); ;
  319.  
  320.             // If both neighbours are on the board and both are walkable.
  321.             if (InBounds(neighbourPoint1) && InBounds(neighbourPoint2) && NodeCreator.nodesList[neighbourPoint1].isWalkable && NodeCreator.nodesList[neighbourPoint2].isWalkable)
  322.             {
  323.                 return true;
  324.             }
  325.         }
  326.         // If the neighbour is up-left of the current.
  327.         if (current.gridPosition.X > neighbour.gridPosition.X && current.gridPosition.Y < neighbour.gridPosition.Y)
  328.         {
  329.             // Neighbour left of the current.
  330.             neighbourPoint1 = new Point(current.gridPosition.X - 1, current.gridPosition.Y);
  331.             // Neighbour above of the current.
  332.             neighbourPoint2 = new Point(current.gridPosition.X, current.gridPosition.Y + 1); ;
  333.  
  334.             // If both neighbours are on the board and both are walkable.
  335.             if (InBounds(neighbourPoint1) && InBounds(neighbourPoint2) && NodeCreator.nodesList[neighbourPoint1].isWalkable && NodeCreator.nodesList[neighbourPoint2].isWalkable)
  336.             {
  337.                 return true;
  338.             }
  339.         }
  340.         return false;
  341.     }
  342.  
  343.     // Colors the final path and sets the next node the zombie needs to walk to.        
  344.     private void FindFinalPath()
  345.     {
  346.         while (finalPath.Count > 0)
  347.         {
  348.             if (2 == finalPath.Count)
  349.             {
  350.                 nextNode = finalPath.Pop();
  351.             }
  352.             current = current.parent;
  353.             finalPath.Pop();
  354.  
  355.             if (current == start)
  356.             {
  357.                
  358.             }
  359.         }
  360.     }
  361.  
  362.  
  363.     // Run all our methods in the correct order.
  364.     public void RunAStar()
  365.     {
  366.         CheckTargetPos();
  367.         //activateAStar = true;
  368.         //isRunning = true;
  369.  
  370.         if (start == null && current == null)
  371.         {
  372.             SetStartNode();
  373.         }
  374.         if (goal == null)
  375.         {
  376.             SetGoalNode();
  377.         }
  378.        
  379.  
  380.         if (activateAStar && start != null && current != null && goal != null)
  381.         {
  382.             while (current != goal)
  383.             {
  384.                 FindPath();
  385.             }
  386.            
  387.  
  388.             FindFinalPath();
  389.             ResetStuff();
  390.         }
  391.     }
  392.  
  393.  
  394.  
  395.     // Checks how close the player and the zombie are.
  396.     private void CheckTargetPos()
  397.     {
  398.         float x = Math.Abs(player.transform.position.x - transform.position.x);
  399.         float y = Math.Abs(player.transform.position.y - transform.position.y);
  400.  
  401.         if (x < 8 && y < 8)
  402.         {
  403.             activateAStar = false; // ik moet hier de astar stoppen!!
  404.             isRunning = false;
  405.         }
  406.         else
  407.         {
  408.             activateAStar = true;
  409.             isRunning = true;
  410.         }
  411.     }
  412.  
  413.     private void ResetStuff()
  414.     {
  415.         Debug.Log("Reset stuff runt");
  416.         openList.Clear();
  417.         closedList.Clear();
  418.         finalPath.Clear();
  419.         current = null;
  420.         start = null;
  421.         goal = null;
  422.     }
  423.  
  424. }
Advertisement
Add Comment
Please, Sign In to add comment