Search code examples
unity-game-engine2dunityscriptpath-finding

Enemy is not following path


I am working in Unity 4.6.2f. I am using Physics2D, UnityScript, and A* pathfinding (http://arongranberg.com/astar/) free version 3.6. My problem is with moving enemy with my EnemyAI script, it shows path correctly in gizmo, but my enemy is not following it. It look like he is always trying to get to the 0th point in the path, and it just flies and shakes in the air.

EnemyAI script - I think problem might be in last 4 lines of code:

import Pathfinding;
@script RequireComponent(Seeker)
@script RequireComponent(Rigidbody2D)

var seeker : Seeker;
var rb : Rigidbody2D;
var path : Path;
var target : Transform;
var updateRate : float = 2f;
var currentWaypoint : int = 0;
var nextWaypointDistance : float;
var pathIsEnded :boolean;
var speed : float = 300f;
var fMode : ForceMode2D;

function Start () {
    rb = GetComponent.<Rigidbody2D>();
    seeker = GetComponent.<Seeker>();
    if (target == null)Debug.LogError("!!!NO PLAYER FOUND!!!");
    //Start the path
    seeker.StartPath(transform.position, target.position,OnPathComplete);
    StartCoroutine(UpdatePath());               
}
//function for finding new way when target moves
function UpdatePath() :IEnumerator {
    if (target == null) {
            //TODO: Insert a player search here.
            return;
        }
        seeker.StartPath (transform.position, target.position, OnPathComplete); 
        yield WaitForSeconds( 1f/updateRate );
        StartCoroutine(UpdatePath());
    }

function OnPathComplete (p:Path) {
        Debug.Log ("We got a path. Did it have an error? " + p.error);
        if (!p.error) {
            path = p;
            currentWaypoint = 0;
        }
}

function FixedUpdate(){
        if (target == null) {
            //TODO: Insert a player search here.
            return;
        }

        //TODO: Always look at player?

        if (path == null)
            return;

        if (currentWaypoint >= path.vectorPath.Count) {
            if (pathIsEnded)
                return;

            Debug.Log ("End of path reached.");
            pathIsEnded = true;
            return;
        }
        pathIsEnded = false;

        //Direction to the next waypoint
        var dir: Vector3 = (path.vectorPath[currentWaypoint] - transform.position).normalized;
        dir *= speed * Time.fixedDeltaTime;

        //Move the AI
        rb.AddForce (dir, fMode);
        Debug.Log(dir);

        var dist:float = Vector3.Distance (transform.position, path.vectorPath[currentWaypoint]);
        if (dist < nextWaypointDistance) {
            currentWaypoint++;
            return;
        }
}

Solution

  • Indeed it seems the problem is in the last 4 lines. Here is a couple of things that could be wrong:

    • You are calculating the distance from the AI and the Target waypoint with Vector3, when you are using 2D coordinates. Make sure both items are working in the same Z coordinate or calculate the distance using only X and Y coordinates.
    • NextWaypointDistance is not set. If the value is a random number and it is a negative number, the player will never "reach" the node.

    Always check your variables are initializated, and when working on 2D, don't just ignore the Z coordinate, it has its uses and it could also mess your distance calculations.