Hi,
I am using a Point Graph in an environment that has objects that need to be avoided moving around in random directions. What I have done is setup up a delayed refresh of the Graph and get a new Path, at a rate of my choosing, currently 0.1 seconds.
Is this the correct / most efficient way of doing this. Below is an example of my script. Thanks!:
`
//Need for A* component
import Pathfinding;
var nextWaypointDistance : float = 0.5; //Range to be within current waypoint before moving on to next
var currentWaypoint : int = 0;
var currentSpeedSetting : float = 0.1;
var NewPathRefreshDelay : float = 0.1;
var pathRefreshDelayIsOn = false;
var targetPosition : Vector3;
var dir : Vector3;
var seeker : Seeker;
var aStar : AstarPath;
var path : Path;
function Start ()
{
aStar = GameObject.Find("_A*").GetComponent(AstarPath);
seeker = GetComponent(Seeker);
transform.LookAt(targetPosition);
}
function Update()
{
GetNewPathUpdateDelay();
}
function GetNewPathUpdateDelay() //Delayed refresh of the path
{
if(pathRefreshDelayIsOn == false)
{
pathRefreshDelayIsOn = true;
targetPosition = GameObject.Find(“Target”).transform.position;
aStar.graphs[0].Scan(); //Rescan Graph 0 incase avoid objects have moved
GetNewPath(); //Note each new patch is given a new number for example “Path Number 21” - It might be useful to know!
yield WaitForSeconds(NewPathRefreshDelay);
pathRefreshDelayIsOn = false;
}
}
function GetNewPath()
{
seeker.StartPath(transform.position, targetPosition, OnPathComplete);
}
function OnPathComplete(newPath : Path) //The newly created path is sent over as “newPath” as type “Path”
{
if(!newPath.error)
{
path = newPath; //Set the path to this new one
currentWaypoint = 0; //Now the Path has been set, make sure we start at the first waypoint
} else {
print(“New Path Error”);
}
}
function FixedUpdate()
{
if(path == null)
{
print("No path!");
}
if(path != null) //This avoids null erros while path is being calculated
{
if (currentWaypoint >= path.vectorPath.Length) //reached end of path?
{
print("End of Path");
}
if(currentWaypoint < path.vectorPath.Length) //If NOT reached end of path then get direction and apply movement
{
dir = (path.vectorPath[currentWaypoint] - transform.position).normalized;
rigidbody.AddForce(dir*currentSpeedSetting);
}
//Check if we are close enough to next waypoint
if (Vector3.Distance (transform.position, path.vectorPath[currentWaypoint]) < nextWaypointDistance)
{
currentWaypoint++; //If we are proceed to next waypoint
}
}
}
`