Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections.Generic;
- using System;
- public class AStar : MonoBehaviour
- {
- // The starting point of our algorithm.
- [SerializeField]
- public NodeScript start;
- // The goal of our algorithm.
- [SerializeField]
- public NodeScript goal;
- // The current point of our algorithm.
- [SerializeField]
- public NodeScript current;
- // The open list.
- HashSet<NodeScript> openList = new HashSet<NodeScript>();
- // The closed list.
- HashSet<NodeScript> closedList = new HashSet<NodeScript>();
- // The finalPath.
- Stack<NodeScript> finalPath = new Stack<NodeScript>();
- // Reference to our Node Creator, the gameobject that instaniates all the nodes.
- NodeCreator boardSize;
- // The monster
- [SerializeField]
- private GameObject zombie;
- // The player
- [SerializeField]
- private PlayerController player;
- // Determines which nodescore this monster is going to use for his calculations.
- private int nodeScoresNumber = 0;
- // The next node the zombie needs to walk to.
- public NodeScript nextNode;
- // Is set to true if AStar has run atleast once.
- public bool isRunning;
- // If this is true, AStar will run.
- public bool activateAStar;
- private void Start()
- {
- activateAStar = true;
- isRunning = false;
- nextNode = null;
- boardSize = GameObject.Find("NodeCreator").GetComponent<NodeCreator>();
- player = GameObject.Find("Character").GetComponent<PlayerController>();
- }
- //tmp values
- float a = .5f;
- float b = .5f;
- private void Update()
- {
- if (Input.GetKeyDown("z") && Time.time > a)
- {
- a = b + Time.time;
- SetStartNode();
- }
- if (Input.GetKeyDown("x") && Time.time > a)
- {
- a = b + Time.time;
- SetGoalNode();
- }
- if (Input.GetKeyDown("c") && Time.time > a)
- {
- a = b + Time.time;
- FindPath();
- }
- if (Input.GetKeyDown("v") && Time.time > a)
- {
- a = b + Time.time;
- FindFinalPath();
- }
- if (Input.GetKeyDown("b") && Time.time > a)
- {
- a = b + Time.time;
- ResetStuff();
- }
- if (Input.GetKeyDown("n"))
- {
- a = b + Time.time;
- //
- }
- RunAStar();
- }
- // Finds our start and current node.
- private void SetStartNode()
- {
- RaycastHit2D hit = Physics2D.Raycast(zombie.transform.position, Vector2.zero);
- if(hit)
- {
- start = hit.collider.gameObject.GetComponent<NodeScript>();
- current = hit.collider.gameObject.GetComponent<NodeScript>();
- openList.Add(current);
- if (start == null)
- {
- Debug.Log("Start = null");
- }
- else
- {
- Debug.Log("Start = set");
- }
- } else
- {
- Debug.Log("Raycast didn't hit.");
- }
- }
- // Finds our goal node. (the player)
- private void SetGoalNode()
- {
- RaycastHit2D hit = Physics2D.Raycast(player.transform.position, Vector2.zero);
- if (hit)
- {
- goal = hit.collider.GetComponent<NodeScript>();
- }
- else
- {
- Debug.Log("Raycast didn't hit.");
- }
- }
- // Finds the path from the start to the goal.
- private void FindPath()
- {
- while (current != goal)
- {
- FindNewCurrentNode();
- openList.Remove(current);
- closedList.Add(current);
- finalPath.Push(current);
- //SpriteRenderer currentSprite = current.GetComponent<SpriteRenderer>();
- //currentSprite.color = Color.cyan;
- // The two for loops make a 3x3 grid around the current node, where the current node is the middle.
- for (int x = -1; x <= 1; x++)
- {
- for (int y = -1; y <= 1; y++)
- {
- Point neighbourPos = new Point(current.gridPosition.X - x, current.gridPosition.Y - y);
- // 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
- if (neighbourPos != current.gridPosition && InBounds(neighbourPos))
- {
- // Uses the Point key to get the corresponding node out of the nodesList.
- NodeScript neighbour = NodeCreator.nodesList[neighbourPos];
- // If the closed list doesn't contain the neighbour && the neighbour is walkable.
- if (!closedList.Contains(neighbour) && neighbour.isWalkable)
- {
- int gCost = 0;
- //Calculates the G cost.
- if (Math.Abs(x - y) == 1)
- {
- neighbour.G = 10;
- gCost = 10;
- }
- else
- {
- if(!DiagonalMoveCheck(current, neighbour))
- {
- continue;
- }
- neighbour.G = 14;
- gCost = 14;
- }
- // Calculates the H cost.
- int hCost = GetDistance(neighbour, goal);
- // Calculates the F cost.
- int fCost = gCost + hCost;
- // If the neighbour's previous fScore is zero || the neighbour isn't in the open list.
- if(neighbour.F == 0 || !openList.Contains(neighbour))
- {
- neighbour.parent = current;
- neighbour.G = gCost;
- neighbour.H = hCost;
- neighbour.F = fCost;
- // If the neighbour's previous fScore is greater then the new fScore && the neighbour isn't in the open list.
- } else if(neighbour.F > fCost || !openList.Contains(neighbour))
- {
- neighbour.parent = current;
- neighbour.G = gCost;
- neighbour.H = hCost;
- neighbour.F = fCost;
- }
- if (!openList.Contains(neighbour))
- {
- openList.Add(neighbour);
- }
- }
- }
- }
- }
- }
- if (current == goal)
- {
- Debug.Log("Path has been found");
- }
- }
- // Returns true if the position is on the board.
- public bool InBounds(Point position)
- {
- return position.X >= 0 && position.Y >= 0 && position.X <= boardSize.x - 1 && position.Y <= boardSize.y - 1;
- }
- // Calculates the distance between the neighbour node and the goal node.
- private int GetDistance(NodeScript neighbour, NodeScript goal)
- {
- int dstX = Mathf.Abs(neighbour.gridPosition.X - goal.gridPosition.X);
- int dstY = Mathf.Abs(neighbour.gridPosition.Y - goal.gridPosition.Y);
- if(dstX > dstY)
- {
- return (14 * dstY) + 10 * (dstX - dstY);
- }
- return (14 * dstX) + 10 * (dstY - dstX);
- }
- // Finds a new current node based on the neighbours lowest F score.
- private void FindNewCurrentNode()
- {
- int fScore = 10000;
- Point point;
- if(current != null && openList.Count > 1) //openList.Count > 1
- {
- foreach (NodeScript nodes in openList)
- {
- if (fScore > nodes.F) // Dit gedeelte geeft de error.
- {
- fScore = nodes.F;
- point = nodes.gridPosition;
- // DEZE 2 regels zou Ik EIGENLIJK ui tde foreach moeten halen.
- // En dan moet ik iets met ref/out doen, omdat de point word niet geupdate buiten de if statement (by reference/by value).
- // Dit zal wss een performance boost geven.
- NodeScript newCurrent = NodeCreator.nodesList[point];
- current = newCurrent;
- }
- }
- }
- }
- // Returns true if the diagonal move is possible, so there aren't any obstacles blocking the path. (Otherwise we could walk over a wall.)
- private bool DiagonalMoveCheck(NodeScript current, NodeScript neighbour)
- {
- Point neighbourPoint1;
- Point neighbourPoint2;
- // If the neighbour is down-right of the current.
- if(current.gridPosition.X < neighbour.gridPosition.X && current.gridPosition.Y > neighbour.gridPosition.Y)
- {
- // Neighbour right of the current.
- neighbourPoint1 = new Point(current.gridPosition.X + 1, current.gridPosition.Y);
- // Neighbour under of the current.
- neighbourPoint2 = new Point(current.gridPosition.X, current.gridPosition.Y - 1); ;
- // If both neighbours are on the board and both are walkable.
- if(InBounds(neighbourPoint1) && InBounds(neighbourPoint2) && NodeCreator.nodesList[neighbourPoint1].isWalkable && NodeCreator.nodesList[neighbourPoint2].isWalkable)
- {
- return true;
- }
- }
- // If the neighbour is down-left of the current.
- if (current.gridPosition.X > neighbour.gridPosition.X && current.gridPosition.Y > neighbour.gridPosition.Y)
- {
- // Neighbour left of the current.
- neighbourPoint1 = new Point(current.gridPosition.X - 1, current.gridPosition.Y);
- // Neighbour under of the current.
- neighbourPoint2 = new Point(current.gridPosition.X, current.gridPosition.Y - 1); ;
- // If both neighbours are on the board and both are walkable.
- if (InBounds(neighbourPoint1) && InBounds(neighbourPoint2) && NodeCreator.nodesList[neighbourPoint1].isWalkable && NodeCreator.nodesList[neighbourPoint2].isWalkable)
- {
- return true;
- }
- }
- // If the neighbour is up-right of the current.
- if (current.gridPosition.X < neighbour.gridPosition.X && current.gridPosition.Y < neighbour.gridPosition.Y)
- {
- // Neighbour right of the current.
- neighbourPoint1 = new Point(current.gridPosition.X + 1, current.gridPosition.Y);
- // Neighbour above of the current.
- neighbourPoint2 = new Point(current.gridPosition.X, current.gridPosition.Y + 1); ;
- // If both neighbours are on the board and both are walkable.
- if (InBounds(neighbourPoint1) && InBounds(neighbourPoint2) && NodeCreator.nodesList[neighbourPoint1].isWalkable && NodeCreator.nodesList[neighbourPoint2].isWalkable)
- {
- return true;
- }
- }
- // If the neighbour is up-left of the current.
- if (current.gridPosition.X > neighbour.gridPosition.X && current.gridPosition.Y < neighbour.gridPosition.Y)
- {
- // Neighbour left of the current.
- neighbourPoint1 = new Point(current.gridPosition.X - 1, current.gridPosition.Y);
- // Neighbour above of the current.
- neighbourPoint2 = new Point(current.gridPosition.X, current.gridPosition.Y + 1); ;
- // If both neighbours are on the board and both are walkable.
- if (InBounds(neighbourPoint1) && InBounds(neighbourPoint2) && NodeCreator.nodesList[neighbourPoint1].isWalkable && NodeCreator.nodesList[neighbourPoint2].isWalkable)
- {
- return true;
- }
- }
- return false;
- }
- // Colors the final path and sets the next node the zombie needs to walk to.
- private void FindFinalPath()
- {
- while (finalPath.Count > 0)
- {
- if (2 == finalPath.Count)
- {
- nextNode = finalPath.Pop();
- }
- current = current.parent;
- finalPath.Pop();
- if (current == start)
- {
- }
- }
- }
- // Run all our methods in the correct order.
- public void RunAStar()
- {
- CheckTargetPos();
- //activateAStar = true;
- //isRunning = true;
- if (start == null && current == null)
- {
- SetStartNode();
- }
- if (goal == null)
- {
- SetGoalNode();
- }
- if (activateAStar && start != null && current != null && goal != null)
- {
- while (current != goal)
- {
- FindPath();
- }
- FindFinalPath();
- ResetStuff();
- }
- }
- // Checks how close the player and the zombie are.
- private void CheckTargetPos()
- {
- float x = Math.Abs(player.transform.position.x - transform.position.x);
- float y = Math.Abs(player.transform.position.y - transform.position.y);
- if (x < 8 && y < 8)
- {
- activateAStar = false; // ik moet hier de astar stoppen!!
- isRunning = false;
- }
- else
- {
- activateAStar = true;
- isRunning = true;
- }
- }
- private void ResetStuff()
- {
- Debug.Log("Reset stuff runt");
- openList.Clear();
- closedList.Clear();
- finalPath.Clear();
- current = null;
- start = null;
- goal = null;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment