I’m in the process of creating simple AI waypoints and have stumbled upon a problem Vector3 distance not being updated.
In the Start function I have a call to a Patrol function. I have created two waypoints and passed them to the AI.
function Patrol () {
//Selects starting waypoint
var curWayPoint = patrolPointA;
while (true) {
var waypointPosition = curWayPoint.transform.position;
//Enemy will rotate and walk towards next waypoint
if (Vector3.Distance(waypointPosition, transform.position) < 0.1){
if(curWayPoint == patrolPointA){
print("B");
curWayPoint = patrolPointB;
waypointPosition = curWayPoint.transform.position;
}else{
curWayPoint = patrolPointA;
print("A");
waypointPosition = curWayPoint.transform.position;
}
}
//Move to target
//MoveToTarget(curWayPoint);
Debug.DrawLine(transform.position, waypointPosition, Color.yellow);
MoveTowards(waypointPosition);
yield;
}
}
I have two functions which I am experimenting with, one gets passed the vector position of the target the other, the actual transform of the target.
The below function receives the transform and works perfectly, but the character has no collision.
function MoveToTarget (targetPosition : Transform){
//Rotate towards target position
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(targetPosition.position - transform.position), rotationSpeed * Time.deltaTime);
//Walk towards waypoint position
transform.position += transform.forward * walkSpeed * Time.deltaTime;
animation.CrossFade("WalkForward", 0.3);
}
The other function recieves the Vector3 position of the current target, but unlike the previous function the AI gets stuck rotating around the first target. For some reason the Vector3 isn’t being updated.
function MoveTowards (position : Vector3) {
Debug.DrawLine(transform.position, position, Color.red);
var direction = position - transform.position;
// Rotate towards the target
transform.rotation = Quaternion.Slerp (transform.rotation, Quaternion.LookRotation(direction), rotationSpeed * Time.deltaTime);
transform.eulerAngles = Vector3(0, transform.eulerAngles.y, 0);
// Modify speed so we slow down when we are not facing the target
var forward = transform.TransformDirection(Vector3.forward);
// Move the character
direction = forward * walkSpeed;
GetComponent (CharacterController).SimpleMove(direction);
animation.CrossFade("WalkForward", 0.3);
}
The waypoint position is being updated, but either the function is broken somehow or the Vector3 position isn’t being updated correctly within the Patrol function.