2D movement along a path

Hello all,

I’ve just got started with the A* pathfinding on a 2D project and it works perfectly to plot the path, but I’m having trouble with getting 2D objects to move properly along that path. The behaviour I’m looking for is similar to a pac man enemy, and I have a simplified scene set up for testing.

I’m able to get the grid to set up perfectly:

These are the settings I’m using (note I have the grid rotated -90 so I can use X Y coordinates):

When I run the code to plot a path that works perfectly, as well:

The problem I’m running into is having an object follow that path properly. I’m seeing a lot of weird, unexpected behaviour for something I though would be rather simple. I used rigidbody physics as opposed to a character controller to get around the weird gravity issues. The main issue I don’t understand is that if I comment out the check for proximity to the NextWaypoint, it simply doesn’t work at all.

Is there a best practice for getting an object to simply move along a plotted path? This is the code I’m using:

`using UnityEngine;
using System.Collections;

using Pathfinding;

public class AstarAI2D : MonoBehaviour {

public Vector3 targetPosition;

private Seeker seeker;

//The calculated path
public Path path;

//Speed per second
public float speed = 4;

//The max distance from the AI to a waypoint for it to continue to the next waypoint
public float nextWaypointDistance = 0.2;

//The waypoint we are currently moving towards
private int currentWaypoint = 0;

//Store the waypoints
public Vector3[] waypoints;

private Vector2 movement;
private Vector3 dir;

public bool ableToMove = true;


// Use this for initialization
void Start () {

	//Get reference to seeker component
	seeker = GetComponent<Seeker>();
	
	seeker.StartPath (transform.position, waypoints[currentWaypoint], OnPathComplete);

}

void Update(){
            
            //Direction to the next waypoint
	dir = (path.vectorPath[currentWaypoint]-transform.position).normalized;

            //Update the movement direction
	movement = new Vector2(speed * dir.x, speed * dir.y);

}

public void OnPathComplete (Path p) {

	Debug.Log ("Did we have an error? " + p.error);
	if (!p.error){			
		path = p;
		//Reset the waypoint counter
		currentWaypoint = 0;
	}
}

public void FixedUpdate(){
	if (path == null){
		print ("No paths yet.");
		//No path to move towards yet
		return;
	}

	if (currentWaypoint >= waypoints.Length){
		Debug.Log("End of Path Reached");
		ableToMove = false;
		currentWaypoint = 0;
		return;
	}

	//Move the rigidbody	
	rigidbody2D.velocity = movement;
		
	//Check if we are close enough to the next waypoint
	//If we are, proceed to the next waypoint
	if (Vector3.Distance (transform.position, path.vectorPath[currentWaypoint]) < nextWaypointDistance){
		currentWaypoint++;
		//return;
	}

}

}
`