- Home /
Question by
yair710 · May 14, 2021 at 02:55 PM ·
gameobjectlistfollow
Help get the enemy to follow the player in the shortest way
I have a code that builds a list that finds the shortest way for the enemy to reach the player. The list is made up of points that are on the map But it does not work it seems to me it is because of the MakePath function the code
public List<NodeScript> AllNodes = new List<NodeScript>();
public NodeScript ClosestNode;
public NodeScript TargetNode;
public Transform Target;
public List<NodeScript> Path;
public Movement mvmt;
public float minDist;
public float maxDist;
void Awake()
{
AllNodes = FindObjectsOfType<NodeScript>().ToList();
}
NodeScript GetClosestNodeTo(Transform t)
{
NodeScript fNode = null;
float minDistance = Mathf.Infinity;
foreach(var node in AllNodes)
{
float distance = (node.transform.position - t.position).sqrMagnitude;
if(distance<minDistance)
{
minDistance = distance;
fNode = node;
}
}
return fNode;
}
void FindPath()
{
Path.Clear();
TargetNode = GetClosestNodeTo(Target);
ClosestNode = GetClosestNodeTo(transform);
if (TargetNode == null || ClosestNode == null)
{
return;
}
HashSet<NodeScript> VisetedNodes = new HashSet<NodeScript>();
Queue<NodeScript> Q = new Queue<NodeScript>();
Dictionary<NodeScript, NodeScript> nodeAndParent = new Dictionary<NodeScript, NodeScript>();
Q.Enqueue(ClosestNode);
while (Q.Count > 0)
{
NodeScript n = Q.Dequeue();
if(n.Equals(TargetNode))
{
MakePath(nodeAndParent);
return;
}
foreach(var node in n.connectedTo)
{
if(! VisetedNodes.Contains(node))
{
VisetedNodes.Add(node);
nodeAndParent.Add(node, n);
Q.Enqueue(node);
}
}
}
}
void MakePath(IDictionary<NodeScript,NodeScript> nap)
{
if (nap.Count > 0)
{
if (nap.ContainsKey(TargetNode))
{
NodeScript cNode = TargetNode;
while(cNode != ClosestNode)
{
Path.Add(cNode);
cNode = nap[cNode];
}
Path.Add(ClosestNode);
Path.Reverse();
}
}
}
class NodeScript
public class NodeScript : MonoBehaviour
{
public List<NodeScript> connectedTo = new List<NodeScript>();
public void OnDrawGizmos()
{
Gizmos.DrawIcon(transform.position, "blendsampler");
foreach(var node in connectedTo)
{
Gizmos.DrawLine(transform.position, node.transform.position);
}
}
}
Comment
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Can't add GameObjects to ArrayList 1 Answer
Keep adding targets to a list 2 Answers
A list of enemies and players speed to determine turn order 2 Answers