I’m hoping to get some help. I’ve found the tutorial very helpful, but I can’t seem to get the polish on this that I’d like. I believe I’m using the exact code from the example.
- My object moves towards the target great, getting around obstacles until it’s almost there. At about the last 10-20% of it’s trip, it begins to really stutter and jump around. As near as I can tell it’s a combination of not being able to find a new path and not knowing that it’s close to reaching the end of it’s path.
- I never see the green line as specified in the tutorial. This is despite disabling the 3d Gizmos setting as recommended
My code is below. I’m happy to post any additional details and/or help to get this tutorial more polished! I’m using the latest version of Unity. Thanks!
`
using UnityEngine;
using System.Collections;
//Note this line, if it is left out, the script won’t know that the class ‘Path’ exists and it will throw compiler errors
//This line should always be present at the top of scripts which use pathfinding
using Pathfinding;
public class AstarAI : MonoBehaviour
{
//The point to move to
public Vector3 targetPosition;
private Seeker seeker;
private CharacterController controller;
//The calculated path
public Path path;
//The AI's speed per second
public float speed = 100;
//The max distance from the AI to a waypoint for it to continue to the next waypoint
public float nextWaypointDistance = 3;
//The waypoint we are currently moving towards
private int currentWaypoint = 0;
public float repathRate = 0.5f;
private float lastRepath = -9999;
public void Start()
{
seeker = GetComponent<Seeker>();
controller = GetComponent<CharacterController>();
}
public void OnPathComplete(Path p)
{
p.Claim(this);
if (!p.error)
{
if (path != null) path.Release(this);
path = p;
//Reset the waypoint counter
currentWaypoint = 0;
}
else
{
p.Release(this);
Debug.Log("Oh noes, the target was not reachable: " + p.errorLog);
}
}
public void Update()
{
if (Time.time - lastRepath > repathRate && seeker.IsDone())
{
lastRepath = Time.time + Random.value * repathRate * 0.5f;
seeker.StartPath(transform.position, targetPosition, OnPathComplete);
}
if (path == null) //We have no path to move after yet
{
return;
}
if (currentWaypoint > path.vectorPath.Count)
{
return;
}
if (currentWaypoint == path.vectorPath.Count)
{
Debug.Log("End Of Path Reached");
currentWaypoint++;
return;
}
//Direction to the next waypoint
Vector3 dir = (path.vectorPath[currentWaypoint] - transform.position).normalized;
dir *= speed;
controller.SimpleMove(dir);
if ((transform.position - path.vectorPath[currentWaypoint]).sqrMagnitude < nextWaypointDistance * nextWaypointDistance)
{
currentWaypoint++;
return;
}
}
}`