A* advice and also offer of free help

Just wondered about pathing and if anyone could advise.

I’ve made an A* script in Javascript, it might be quite slow and uses unoptimal arrays for storing data.

I had figured that in order to make things fast I would only run the script once in a while, and on certain characters, this way it could be used sparingly like a sonar?

Is this the approach that people use on AI as it certainly cant just run continuously, or can it?

My code is in Javascript and would be generally considered unoptimal. The reason I ask is, I would like to share notes before I embark on my next coding marathon as the A* took me a week of 10+ hour days.

I dont think many people have achieved even getting this far so I am also offering help with A* scripting. Tutorials will go on my blog at www.planet44.wordpress.com and I’ll also answer questions here. Reason being, it makes my knowledge clearer if I can help others, and it feels good to pretend I am a know it all(which I am, honest).

Are you using a closed list with the A*? What data structures are you using for the lists? The closed list will greatly reduce the number of positions that get searched, and it is very efficient when implemented with a Hashtable. A priority queue is probably the best way to implement the open list, but it is quite easy to code this inefficiently if you are not careful. Is there any chance you can post the code you’ve got for a bit of constructive feedback?

There are also many other things you can do to improve A* performance, but they might depend on the design of the game. Can you describe roughly how the pathing is done in the game, what kind of search graph and obstacles you have and what heuristic you are using? Unless you have a huge playing area, you probably don’t need to ration the use of pathfinding too much.

Yes it is basically on my blog here http://www.planet44.wordpress.com

and here is the actual code however bear in mind I am almost new to this language. I had to learn arrays and the various functions as I went. I took the option of simplicity and now need to work back through and optimise.

var allNodeName = new Array(); // list of all names
var allNodeList = new Array(); // list of all nodes
var localNodeList = new Array(); // to hold all neighbours
var localNodeName = new Array(); // to store all names
var localNodeAG = new Array(); // to store AG
var nodeList = new Array(); // list of nodes
var playerList = new Array(); // list of nodes near player
var openList = new ArrayList(); // open list to be considered
var closedList = new ArrayList(); // closed list not to be considered
var searchRadius = 100; // radius to find nearest nodes
var lm_layerMask : LayerMask; // only look for waypoints
var activeNode : Object;
var initialise = false;
var activeNodeList = new Array();
var allNodeParent = new Array();
var activeNodeListIndex = new Array();
var activeNodeListAF = new Array();
var activeNodeListAG = new Array();
var activeNodeListAH = new Array();
var activeNodeListAFCondensed = new Array();
var canUseNodeList = new ArrayList();
var route = new Array();
var routeNode : Object;

private var distanceNode = new Array(); // establish to hold distances of AI near nodes
private var playerNode = new Array(); // establish to hold distances of player near nodes
private var af = new Array(); // F value of Algorithm in F=G+H
private var ag = new Array(); // G value of Algorithm, distance cost
private var ah = new Array(); // H value of Algorithm, Heuristic
private var localNodeListBuilder = new Array();
private var fwd : Vector3;

var minvalue = 100000;
var start : Object;
var finish : Object;
var hit : RaycastHit;
var localNodeDirection : Vector3;
var localNodeListVetted = new Array();
var lv = 0;
var smallest = 10000;
var minimum = 10000;
var index = 0;
var indexlocal = 0;


//where a is an object eg start then x returns key
function returnkeyfromobject(a)
{
for (x=0; x < allNodeList.length; x++)
{
if(a == allNodeList[x])
{
return x;
}
}
}

// tells you localnodelist value for a = start square
function returnlocalkeyfromobject(a, b)
{
a = returnkeyfromobject(a);
b = returnkeyfromobject(b);
for (x=0; x < localNodeList.length; x++)
{
if(allNodeList[x] == localNodeList[a][b])
{
return x;
}
}
}

function Update()
{
if(initialise == false)
{
//only run the initialisation once
initialise = true;

//Get list of all nodes via overlap sphere
allNodeList = Physics.OverlapSphere(transform.position, 1000000, lm_layerMask);  //find all

//for each one generate a local nodelist
for (var i = 0; i < allNodeList.length; i++)
{
localNodeListBuilder = Physics.OverlapSphere(allNodeList[i].transform.position, searchRadius, lm_layerMask);

//clear vetted list
localNodeListVetted.Clear();

lv = 0;
//for each one check if it is visible
for (ln = 0; ln < localNodeListBuilder.length; ln++)
{
//facing sphere does not work, instead use direction 
localNodeDirection = localNodeListBuilder[ln].transform.position - allNodeList[i].transform.position;

//raycast
if (Physics.Raycast (allNodeList[i].transform.position, localNodeDirection, hit, searchRadius))
{

//determine what was hit
if (hit.collider == localNodeListBuilder[ln])
{
//add to list of vetted nodes
localNodeListVetted[lv] = localNodeListBuilder[ln];
lv++;
}
}
}

//initialise 2D arrays
localNodeList[i] = new Array();
localNodeAG[i] = new Array();

// populate 2D array excluding start node
for (var ab = 0; ab < localNodeListVetted.length; ab++)
{

//populate with list
localNodeList[i][ab] = localNodeListVetted[ab];

//populate with distances
localNodeAG[i][ab] = (allNodeList[i].transform.position - localNodeList[i][ab].transform.position).magnitude;
if(localNodeAG[i][ab] < 1)
{
localNodeAG[i][ab] = 10000;
}

}

//get names
allNodeName[i] = allNodeList[i].name;

}

//Find start

nodeList = Physics.OverlapSphere(transform.position, searchRadius, lm_layerMask); // find list of nodes

	for (var e=0; e< nodeList.length;e++)
	{
	distanceNode[e] = (nodeList[e].transform.position - transform.position).magnitude; //calculate distance to node
		
	// find nearest neighbour
	if(distanceNode[e] < minvalue)
	{
	minvalue = distanceNode[e]; // iteratively find nearest node
	start = nodeList[e]; // return the name to look up in index
	}
	}
	
	Debug.Log("Start is " + start.name);
		
	minvalue = 100000; // Reset minvalue
	
	//find finish
	
	playerList = Physics.OverlapSphere(GameObject.FindWithTag("Player").transform.position, searchRadius, lm_layerMask); //nodelist from player
	for (var l=0; l< playerList.length; l++)
	{
	playerNode[l] = (playerList[l].transform.position - GameObject.FindWithTag("Player").transform.position).magnitude; //calculate distance to node
	
	// find nearest neighbour
	if(playerNode[l] < minvalue)
	{
	minvalue = playerNode[l]; // iteratively find nearest node
	finish = playerList[l]; // return the name to look up in index
	}
	}
	
	Debug.Log("Finish is " + finish.name);
				
	//add start as the active node
	activeNode = start;
		
	// add G value of 0 for start
	activeNodeListAG[returnkeyfromobject(start)] = 0;
	
	//add self as parent for start
	allNodeParent[returnkeyfromobject(start)] = start;
	
	// add start to closed list
    closedList.Add(start);
		
	//initialise variables
	var key = 0;
	var activeAG = 0;
	var parentSquare = new Array();
	parentSquare.Push("Self");
	var parentCost = 0;
	var heuristicPlayerPosX = 0;
	var heuristicPlayerPosZ = 0;
	var squareX = 0;
	var squareZ = 0;
	var differenceX = 0;
	var differenceZ = 0;
	var heuristicX = 0;
	var heuristicZ = 0;
	var minaf = 10000;
	var activeNodeSelect = 0;
	
	//A* Main Loop
	for(var al = 0; al < allNodeList.length; al++)
	{
	//get index in allNodeList
	key = returnkeyfromobject(activeNode);
			
	//add neighbours into open list if they are not already there
	for(var bl = 0; bl < localNodeList[key].length; bl++)
	{
	
	if(!closedList.Contains(localNodeList[key][bl]))
	{
	if(!openList.Contains(localNodeList[key][bl]))
	{
	openList.Add(localNodeList[key][bl]);
	Debug.Log("new square added " + localNodeList[key][bl].name);
	//add the parent square
	Debug.Log("parent " + activeNode.name + "(this activenode) added to " + localNodeList[key][bl].name);
	allNodeParent[returnkeyfromobject(localNodeList[key][bl])] = activeNode;
	}
	}
	}
	
	//if finish is found in openList then finish
	if(openList.Contains(finish))
	{
	Debug.Log("Finish Found");
	break;
	}
	
	//go through openList and populate values
	for(j = 0; j < openList.Count; j++)
	{
	//get indexes
	index = returnkeyfromobject(openList[j]);
	
	// run if not on closed and on open
	if(!closedList.Contains(allNodeList[index]))
	{
	if(openList.Contains(allNodeList[index]))
	{
	
	// H values
	heuristicPlayerPosX = (GameObject.FindWithTag("Player").transform.position.x);
	heuristicPlayerPosZ = (GameObject.FindWithTag("Player").transform.position.z);
	squareX = allNodeList[returnkeyfromobject(openList[j])].transform.position.x;
	squareZ = allNodeList[returnkeyfromobject(openList[j])].transform.position.z;
	differenceX = squareX - heuristicPlayerPosX;
    differenceZ = squareZ - heuristicPlayerPosZ;
	heuristicX = Mathf.Sqrt((Mathf.Pow(differenceX, 2)));
	heuristicZ = Mathf.Sqrt((Mathf.Pow(differenceZ, 2)));
	activeNodeListAH[returnkeyfromobject(openList[j])] = heuristicX + heuristicZ;
	
	// total G = localAG + parentAG
	activeNodeListAG[index] = ((allNodeList[index].transform.position - allNodeParent[index].transform.position).magnitude) + activeNodeListAG[returnkeyfromobject(allNodeParent[index])];
		
	//calculate F
	activeNodeListAF[index] = (activeNodeListAH[index] + activeNodeListAG[index]);
		
	activeNodeListAFCondensed.Push(activeNodeListAF[index]);
	activeNodeListIndex.Push(allNodeList[index]);
	
	//debug
	// Debug.Log("Node: " + openList[j].name);
	// Debug.Log("F: " + activeNodeListAF[index]);
	// Debug.Log("G: " + activeNodeListAG[index]);
	// Debug.Log("H: " + activeNodeListAH[index]);
	
	}
	}
	}
	
	smallest = 10000;
		
	//find the index of the smallest af on the activeNodeList
	for(var bf = 0; bf < activeNodeListIndex.Count; bf++)
	{
	Debug.Log("on the activeNodeList " + activeNodeListIndex[bf].name);
	if(activeNodeListAFCondensed[bf] < smallest)
	{
	//if not on closed list
	if(!closedList.Contains(activeNodeListIndex[bf]))
	{
	activeNode = activeNodeListIndex[bf];
	smallest = activeNodeListAFCondensed[bf];
	}
	}
	
	}
	
	Debug.Log("new active Node is " + activeNode.name);
	
	// push to activeNodeList
	canUseNodeList.Add(activeNode); // this is a list of all squares which can be used to backtrack to find route
	activeNodeList.Push(activeNode);
	
	minimum = 10000;
					
	// add to closed list
	closedList.Add(activeNode);
	
	//remove from open list
	openList.Remove(activeNode);
				
    //clear arrays
	af.Clear();
	
	//reaches finish so exit loop
	if(allNodeList[key] == finish)
	{
	Debug.Log("Finish has been reached");
	break;
	}
	}
		
	} // initialisation bracket
	
	route.Clear();
	route.Push(finish);
	routeNode = returnkeyfromobject(finish);
		
	//trace route
	for(x = 0; x < allNodeList.length; x++)
	{
	route.Push(allNodeParent[routeNode]);
	routeNode = returnkeyfromobject(allNodeParent[routeNode]);
	//exit when reaches start
	if(allNodeList[routeNode] == start)
	{
	Debug.Log("list compiled");
	break;
	}
	}
	
	//reverse list
	route.Reverse();
		
	//list is complete
	Debug.Log("route = ");
	for(xl = 0; xl < route.length; xl++)
	{
	Debug.Log(route[xl].name);
	}
	Debug.Log("list completed");
			
	//draw the node connections
	for (x = 0; x < localNodeList.length; x++)
	{
	for (y = 0; y < localNodeList[x].length; y++)
	{
	Debug.DrawLine (allNodeList[x].transform.position, localNodeList[x][y].transform.position, Color.red);
	}
	}
	
	}

A few things that should immediately speed things up…

At the start of the heuristic calculation, you have these two lines:-

heuristicPlayerPosX = (GameObject.FindWithTag("Player").transform.position.x);
heuristicPlayerPosZ = (GameObject.FindWithTag("Player").transform.position.z);

Using GameObject.FindWithTag is relatively slow, since it has to search many GOs to find the one you’re looking for. Instead, find the player object once and store it in a variable.

As for calculating the heuristic, you seem to be using the “Manhattan” distance, where the horizontal and vertical differences are added together. This is appropriate if the player moves on a rectilinear grid (like a chessboard) where only horizontal and vertical moves are possible. If this is correct, you can save some overhead on these two lines:-

heuristicX = Mathf.Sqrt((Mathf.Pow(differenceX, 2))); 
heuristicZ = Mathf.Sqrt((Mathf.Pow(differenceZ, 2)));

Here, you are taking the square root of X^2, which is just X, so these lines just ensure the result is positive and you can use Mathf.Abs to do that. This is significant because the Sqrt and Pow functions are quite CPU-hungry. (General tip: use x * x rather than Pow(x, 2) - it’s much faster.) If the player can move in any direction between adjacent nodes, then the Manhattan distance is not a correct estimate and will lead to reduced speed and suboptimal paths. In this case, just use Vector3.Distance or get the magnitude of the difference of the two positions as you do elsewhere in the code.

After these, the next most obvious improvement is to use a Hashtable for the closed list. Currently, you use ArrayList.Contains to check a node’s presence on the closed list. However, this function works by searching through all items in the list one at a time until the desired item is found. As you can imagine, the closed list gets very large as the algorithm progresses, and so the search gets increasingly inefficient. A Hashtable, on the other hand, maintains more or less constant efficiency regardless of the size of the list. The code for checking the Hashtable is almost the same as for the ArrayList (they both have a Contains function) so you shouldn’t have to modify the code much.

The sky’s the limit with A* optimisation, but you should find these things will make things quite a bit faster with little effort.

This is really very useful indeed.

Yes I did know about gameObject.Findwithtag however I got so lost that I wanted to get it working and then come back to optimisation.

My original question does remain though(and not moaning because your answer is extremely useful in many ways and will keep me busy), are people running these scripts intermittently?

I dont understand the whole process wherin for instance Update is run each frame, and how people generally place costly pieces of code into games, so that they are not performed all at once, or even when they do run that they dont cause slowdown glitches.