In my project I have a route made by waypoints ranging from enemy to player (on a spherical world) what I want to do is to use coroutiner to walk the enemy. I’ve seen tutorials but the coroutiner should calculate the path to each frame. Only that works well in Start (). Do you know how to help me?
public class Test : MonoBehaviour {
public Transform t1, t2, node, planet;
public int division, index;
private List<Waypoint> nodes;
Vector3 direction, nodeDirection;
float dist, result, y;
public float fraction, startTime;
void Start()
{
nodes = new List<Waypoint>();
dist = Vector3.Distance(t1.position, t2.position);
direction = (t2.position - t1.position).normalized;
for (int i = 0; i < division; i++)
{
result = (dist / division) * i;
Vector3 wayPointPos = new Vector3(SetPos(direction.x, result, t1.position.x),
SetPos(direction.y, result, t1.position.y),
SetPos(direction.z, result, t1.position.z));
Vector3 normalWay = wayPointPos.normalized;
//Transform t = Instantiate(node, normalWay * 6f,Quaternion.identity) as Transform;
Waypoint t = new Waypoint(normalWay * 3f);
nodes.Add(t);
Debug.Log(nodes[i].pos);
}
}
#region Update
void Update()
{
dist = Vector3.Distance(t1.position, t2.position);
direction = (t2.position - t1.position).normalized;
nodes.Clear();
for (int i = 0; i < division; i++)
{
result = (dist / division) * i;
Vector3 wayPointPos = new Vector3(SetPos(direction.x, result, t1.position.x),
SetPos(direction.y, result, t1.position.y),
SetPos(direction.z, result, t1.position.z));
Vector3 normalWay = wayPointPos.normalized;
//Transform t = Instantiate(node, normalWay * 6f,Quaternion.identity) as Transform;
Waypoint t = new Waypoint(normalWay * 3f);
nodes.Add(t);
}
StartCoroutine(followPath());
}
void OnDrawGizmos()
{
if (nodes != null)
{
foreach (Waypoint item in nodes)
{
Gizmos.color = Color.blue;
Gizmos.DrawWireCube(item.pos, Vector3.one * 0.2f);
}
}
}
IEnumerator followPath()
{
Vector3 currentPoint = nodes[0].pos;
if (nodes.Count != 0)
{
while (true)
{
if (t1.position == currentPoint)
{
index++;
if (index >= nodes.Count)
{
yield break;
}
currentPoint = nodes[index].pos;
}
t1.transform.position = Vector3.MoveTowards(t1.transform.position, currentPoint, 2f);
yield return new WaitForSeconds(0.03F);
}
}
}
#endregion
float SetPos(float direction, float result, float enemyPosition)
{
return (direction * result) + enemyPosition;
}
float GetAngleInRad(Vector3 v1, Vector3 v2)
{
return Vector3.Angle(v1, v2);
}
}
class Waypoint
{
public Vector3 pos;
public Waypoint(Vector3 postion)
{
this.pos = postion;
}
}