// Update is called once per frame void Update() { if (Input.GetMouseButtonDown(0)) { // Get position targetPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition); if (!CheckPointInObstacle(targetPosition)) { // Reset path path.Clear(); currentTarget = Vector2.zero; // Get Closest Node float sourceDist = float.MaxValue; float targetDist = float.MaxValue; foreach (Cell c in graph.nodes) { // Source float distance = (c.position - (Vector2)transform.position).sqrMagnitude; if (distance < sourceDist) { sourceDist = distance; closestSourceNode = c; } // Target distance = (c.position - (Vector2)targetPosition).sqrMagnitude; if (distance < targetDist) { targetDist = distance; closestTargetNode = c; } } // Plan Path List <GraphEdge> edges = new List <GraphEdge>(); if (!GraphSearch.AStar(graph, closestSourceNode, closestTargetNode, Euclidean, out edges)) { Debug.Log("No path from source to target."); return; } /* * path.Enqueue(closestSourceNode.position); * foreach(GraphEdge e in edges) * path.Enqueue(((Cell)e.to).position); * path.Enqueue(targetPosition); */ path = PathSmoothing(edges); currentTarget = path.Dequeue(); isMoving = true; } } if (!isMoving) { return; } // Check is target arrived at if (Mathf.Approximately(((Vector2)transform.position - currentTarget).sqrMagnitude, 0f)) { if (path.Count != 0) { currentTarget = path.Dequeue(); } else { isMoving = false; } } // Move transform.position = Vector2.MoveTowards(transform.position, currentTarget, speed * Time.deltaTime); }