Hello all,
I have an NPC patrolling a list of transforms and when reaching the last one he waits for 3 seconds and then turns around and goes through the list but backwards, I’m using a bool (forward) to know to which direction he is moving
public class ParentController : MonoBehaviour
{
List<Transform> waypoints;
[SerializeField] int waypointIndex = 0;
[SerializeField] Transform pathPrefab;
[SerializeField] float moveSpeed;
[SerializeField] int waitTime;
Vector3 targetPosition;
[SerializeField] bool forward = true;
bool llamada = false;
Transform pivot;
Vector3 lookAt;
//pivot.up = targetPosition - pivot.position;
void Awake()
{
waypoints = GetWaypoints();
pivot = transform.Find("Pivot");
}
void Update()
{
MoveParent();
pivot.up = lookAt;
}
void MoveParent()
{
if(waypointIndex < waypoints.Count && forward)
{
Vector3 targetPosition = waypoints[waypointIndex].position;
lookAt = targetPosition - pivot.position;
float delta = moveSpeed * Time.deltaTime;
transform.position = Vector2.MoveTowards(transform.position, targetPosition, delta);
if (transform.position == targetPosition)
{
waypointIndex++;
if(waypointIndex == waypoints.Count && !llamada)
{
StartCoroutine(TurnAround());
}
}
}
if(waypointIndex >= 0 && !forward)
{
Vector3 targetPosition = waypoints[waypointIndex].position;
lookAt = targetPosition - pivot.position;
float delta = moveSpeed * Time.deltaTime;
transform.position = Vector2.MoveTowards(transform.position, targetPosition, delta);
if (transform.position == targetPosition)
{
waypointIndex--;
if(waypointIndex == -1 && !llamada)
{
StartCoroutine(TurnAround());
}
}
}
}
IEnumerator TurnAround()
{
llamada = true;
yield return new WaitForSecondsRealtime(waitTime);
if(waypointIndex >= waypoints.Count)
{
waypointIndex --;
}
else
{
waypointIndex ++;
}
forward = !forward;
llamada = false;
}
List<Transform> GetWaypoints()
{
List<Transform> waypoints = new List<Transform>();
foreach (Transform child in pathPrefab)
{
waypoints.Add(child);
}
return waypoints;
}
}
The code could probably be better but it’s working, now the issue is that the NPC has a “Vision cone” child attached (referenced in the code as “Pivot”).
Pivot is rotating towards the direction the NPC is moving but when reaching the last and first waypoints the pivot turns to Z = 80.554 and not sure what’s causing this and how could I make it so it stays looking at the same direction it was looking before reaching destination.
Thanks in advance