Pathfindingsystem Script for Waypoints doesn't work.
Hey guys, so I wrote this script:
public float speed;
public int currentWayPoint;
public Transform[] Waypoints;
Transform targetWayPoint;
void Update ()
{
if (currentWayPoint < this.Waypoints.Length)
{
if (targetWayPoint == null)
targetWayPoint = Waypoints [currentWayPoint];
Walk ();
}
}
void Walk ()
{
transform.forward = Vector3.RotateTowards (transform.forward, targetWayPoint.position - transform.position, speed * Time.deltaTime, 0.0f);
transform.position = Vector3.MoveTowards (transform.forward, targetWayPoint.position, speed * Time.deltaTime);
if (transform.position == targetWayPoint.position)
{
currentWayPoint ++ ;
targetWayPoint = Waypoints [currentWayPoint];
}
}
The object should go from one waypoint to the other and so on. But as soon as I hit play the object teleports itself to the player gameobject and I don't know why.
It teleports to the center of the world for some reason
Answer by Lilius · Oct 20, 2016 at 02:48 PM
Change this line:
transform.position = Vector3.MoveTowards (transform.forward, targetWayPoint.position, speed * Time.deltaTime);
To be:
transform.position = Vector3.MoveTowards (transform.position, targetWayPoint.position, speed * Time.deltaTime);
tranform.forward returns direction as values between -1 and 1 and transform.position returns the coordinates of actual position of your object. Hope this clears things out, I'm quite new with these things and not english so I'm not always good with the terminology.
I have upgraded my script:
public float speed;
public int currentWayPoint;
public Transform[] Waypoints;
public bool FixedRotation;
public bool Loop = true;
private Quaternion FixedRotate;
Transform targetWayPoint;
void Start ()
{
this.transform.rotation = FixedRotate;
}
void Update ()
{
if (currentWayPoint < this.Waypoints.Length)
{
if (targetWayPoint == null)
targetWayPoint = Waypoints [currentWayPoint];
Walk ();
}
if (FixedRotation)
{
transform.rotation = FixedRotate;
}
}
void Walk ()
{
transform.forward = Vector3.RotateTowards (transform.forward, targetWayPoint.position - transform.position, speed * Time.deltaTime, 0.0f);
transform.position = Vector3.$$anonymous$$oveTowards (transform.position, targetWayPoint.position, speed * Time.deltaTime);
if (this.transform.position == targetWayPoint.position)
{
if (currentWayPoint == Waypoints.Length & Loop)
{
targetWayPoint = Waypoints[0];
}
else if (currentWayPoint == Waypoints.Length & !Loop)
{
GetComponent<WaypointPathFinding> ().enabled = false;
}
else
{
currentWayPoint ++ ;
targetWayPoint = Waypoints[currentWayPoint];
}
}
}
}
Now it says that there is a NullReferenceException. I want it to Loop when the last waypoint is hit. I want it to reset and target the first waypoint again.
Try it like this: if (currentWayPoint == (Waypoints.Length -1) & Loop)
if you have 3 waypoints, waypoints are 0,1,2 but the length is 3.
Your answer
