public class AIController : MonoBehaviour
{
private List points;
private int index;
private bool isRunning = false;
private float tolerance = 0.5f;
void Start()
{
points = new List<Vector3> { new Vector3(5, 5, 0), new Vector3(-5, -5, 0), new Vector3(3, 3, 0) };
}
void Update()
{
if (!isRunning)
{
StartCoroutine(MoveCommand(transform, points));
}
}
private IEnumerator MoveCommand(Transform transform_, List<Vector3> points)
{
while (index < points.Count)
{
var nextPoint = points[index];
transform_.position = Vector3.MoveTowards(transform_.position, nextPoint, (1 * Time.deltaTime));
while (!IsPointReached(transform_, nextPoint, tolerance))
{
yield return null;
}
index++;
}
index = 0;
yield break;
}
private bool IsPointReached(Transform transform_, Vector3 destiny, float tolerance)
=> ((transform_.position.x <= (destiny.x + tolerance) &&
transform_.position.x >= (destiny.x - tolerance)) &&
(transform_.position.y <= (destiny.y + tolerance) &&
transform_.position.y >= (destiny.y - tolerance)));
}
Hi everyone!
So I want to move my transform through a list of points. Initially this script works fine, the transform goes to points[0], then to points[1] and finally points[2]. The coroutine ends and it’s run again, but this time, for some reason it ommits points[0], and it bounces between points[1] and points[2]
Can someone explain me why?