Hi, I wrote this script for pathfinding:
using UnityEngine;
using System.Collections;
public class SmartMove : MonoBehaviour {
Transform[] pathNodes;
public void CalculatePath(Transform startingNode, Transform destinationNode) {
pathNodes = new Transform[1];
AddNode(startingNode, startingNode, destinationNode, false);
}
void AddNode(Transform nodeToAdd, Transform startingNode, Transform destinationNode, bool hasReachedDestination) {
if(!hasReachedDestination) {
Transform[] tempOpenNodes = new Transform[pathNodes.Length+1];
tempOpenNodes[pathNodes.Length] = nodeToAdd;
pathNodes = new Transform[tempOpenNodes.Length];
pathNodes = tempOpenNodes;
CalculateOpenNodes(nodeToAdd, startingNode, destinationNode);
}
if(hasReachedDestination)
GameObject.Find("PathfindingManager").GetComponent<PathfindingTest>().TakePath(pathNodes);
}
void CalculateOpenNodes(Transform currentNode, Transform startingNode, Transform destinationNode) {
bool atDestination = false;
Transform currentBestNode = null;
Transform[] neighbors = currentNode.GetComponent<Tile>().neighbors;
foreach(Transform currentNeighbor in neighbors) {
if (currentNeighbor != null) {
if (currentBestNode == null)
currentBestNode = currentNeighbor;
int F = (int)Mathf.Round(Vector3.Distance(currentNeighbor.position, startingNode.position));
int H = (int)Mathf.Round(Vector3.Distance(currentNeighbor.position, destinationNode.position));
int currentG = F + H;
int smallestF = (int)Mathf.Round(Vector3.Distance(currentBestNode.position, startingNode.position));
int smallestH = (int)Mathf.Round(Vector3.Distance(currentBestNode.position, destinationNode.position));
int smallestG = smallestF + smallestH;
if(currentG < smallestG)
currentBestNode = currentNeighbor;
if (currentNeighbor == destinationNode)
atDestination = true;
}
}
AddNode(currentBestNode, startingNode, destinationNode, atDestination);
}
}
It’s a very simplified version of A* pathfinding as explained here. I’m a fairly inexperienced programmer, so this has been a real challenge to come up with. However, it crashes the editor, and I can’t figure out why. Could somebody please give it a quick run through and point out any obvious mistakes?
Thanks, Havoc
EDIT: Aaaand the script looks like crap. You’ll have to copy it into your favorite text editor to decode it. Sorry about that, can’t format any better. >.<