So I made this pathfinding script that can walk around walls. Problem is that it can get in a situation where 2 tiles/nodes are equally close to the target position and the path makes a little circle before going to the target and in more narrow situations might not be able to get to target at all.
btw. the path cant move diagonally. This is on purpose.
Here are some pictures to help explain. (Start is green tile and target is red tile)
In the first picture the path is optimal but in the second it isnt due to the path going left when it hits the wall.
[50824-pathfinding-fig-1.png*|50824]
[50825-pathfinding-fig-2.png*|50825]
Heres my script (test code. sorry for mess):
public Transform target;
public Vector3[] rayOrigin = new Vector3[4];
RaycastHit[] hit = new RaycastHit[4];
Transform targetTile;
Transform lastTargetTile;
float oldVal = 1000;
bool targetInRange = false;
public List<Transform> openList = new List<Transform>();
public List<Transform> closedList = new List<Transform>();
void Start ()
{
lastTargetTile = transform;
openList.Add(transform);
StartCoroutine(CoTest());
}
IEnumerator CoTest()
{
while(!targetInRange)
{
FindNearestNodes();
yield return new WaitForSeconds(0.5f);
}
}
void FindNearestNodes()
{
rayOrigin[0] = lastTargetTile.position + lastTargetTile.forward + lastTargetTile.up;
rayOrigin[1] = lastTargetTile.position + lastTargetTile.right + lastTargetTile.up;
rayOrigin[2] = lastTargetTile.position - lastTargetTile.forward + lastTargetTile.up;
rayOrigin[3] = lastTargetTile.position - lastTargetTile.right + lastTargetTile.up;
for (int i = 0; i < 4; i++)
{
Debug.DrawRay(rayOrigin*, Vector3.down, Color.red);*
if (Physics.Raycast(rayOrigin_, Vector3.down, out hit*, 2))
{_
_if (hit.transform.CompareTag(“Tile”))
{_
_openList.Add(hit.transform);
}_
_else if (hit.transform == target)
{
targetInRange = true;
}
}
}
if(!targetInRange)
ChooseTargetNode();
}*_
void ChooseTargetNode()
{
Transform[] tempArray = openList.ToArray();
for (int i = 0; i < tempArray.Length; i++)
{
float dist = Vector3.Distance(target.position, tempArray*.position);*
if (dist < oldVal)
{
targetTile = tempArray*;*
oldVal = dist;
}
}
ChangeColor(Color.yellow, targetTile.GetComponent());
oldVal = 1000;
closedList.Add(targetTile);
targetTile.tag = “Untagged”;
openList.Clear();
lastTargetTile = targetTile;
targetTile = null;
}
void ChangeColor(Color c, MeshRenderer meshrenderer)
{
meshrenderer.material.color = c;
}
*
*