Hey guys, i’m trying to create a game tile based 2D, top view, with random map generating. Well everithing was going fine until i decide create a function for pathfinding, the idea was to use it in many ways on the game, first to be sure that the exit is acessible and then for the future IA. The problem is when i press play unity stop working, i think it enters in an infinite loop i just don’t know why, this function receive 2 (vector3), it use the vector3 list (that have the position of all tiles and walls created on the map) to find the path from one point to another, after that it return a list with all the positions of that path.
I believe its a simple code and i hope someone can help me, anyway here it is:
List<Vector3> PathFinding(Vector3 begin, Vector3 end){
List<Vector3> open, closed, caminho;
open = new List<Vector3> ();
closed = new List<Vector3> ();
caminho = new List<Vector3> ();
Vector3 current, proximo;
current = begin;
while (current != end) {
caminho.Add (current);
proximo = new Vector3 (current.x + mapgen.tileSize, current.y, current.z); // Check Right
if (!mapgen.createdWall.Contains (proximo) && !closed.Contains (proximo) ){
open.Add (proximo);
}
proximo = new Vector3 (current.x - mapgen.tileSize, current.y, current.z); // Check Left
if (!mapgen.createdWall.Contains (proximo) && !closed.Contains (proximo) ){
open.Add (proximo);
}
proximo = new Vector3 (current.x, current.y - mapgen.tileSize, current.z); // Check Down
if (!mapgen.createdWall.Contains (proximo) && !closed.Contains (proximo) ){
open.Add (proximo);
}
proximo = new Vector3 (current.x, current.y + mapgen.tileSize, current.z); // Check Up
if (!mapgen.createdWall.Contains (proximo) && !closed.Contains (proximo) ){
open.Add (proximo);
}
proximo = current;
//For all the possible positions to move, find the one with short distance to target point
for(int i = 0; i < open.Count; i++){
if (!caminho.Contains(open_) && (Distancia (open*, end) < Distancia (proximo, end))) {*_
_ proximo = open*;
}
//If there is only one possible movement, that means end up in a dead end.
//Remove the current position from caminho and block that position to no longer be a possible movement*
if ((open.Count == 1) && caminho.Contains(open*)) {
closed.Add (current);
caminho.Remove (current);
}
}
open.Clear();
current = proximo;
}
return caminho;*_
* }*
* //-------------------------- RETURN THE DISTANCE BETWEEN 2 POINTS --------------------------------------------------*
* float Distancia(Vector3 end, Vector3 start){*
* float distance;*
* distance = Mathf.Sqrt(Mathf.Pow((end.x - start.x),2) + Mathf.Pow((end.y - start.y),2));*
* return distance;*
* }*
PS: I didn’t use nodes for this map, its only list of vector3 and each element is a object with a sprite.
PS²: Sorry if i made mistakes in english.