- Home /
Question by
riluril · Feb 22, 2019 at 07:27 AM ·
coroutinemovetowards
Moving object by path
I am trying to make an gameobject move by path (from point to point). Everything works fine, but somethimes gameobject just stopes and can not continue its movement. Coroutine for start movement and settings some params after reaching end of path.
IEnumerator SetObject(SomeObject someObject) {
this.someObject = Instantiate(someObject, path[0].transform);
this.someObject.OrderInLayer = childrenOrderInLayer;
yield return Move(new Queue<PathPoint>(path));
this.someObject.Direction =someObjectDirectionAtStayPoint;
this.someObject.Init();
}
Couroutine for moving by all points of path
IEnumerator Move(Queue<PathPoint> path, bool movingBack = false) {
PathPoint nextPoint = null;
someObject.Direction = (SomeObjectDirection)(movingBack ? (-1) * (int)someObjectDirectionAtPath : (int)someObjectDirectionAtPath);
if (!movingBack) {
nextPoint = path.Dequeue();
someObject.State = nextPoint.SomeObjectState;
}
while (path.Count > 0)
{
nextPoint = path.Dequeue();
if (movingBack) someObject.State = nextPoint.SomeObjectState;
yield return MoveFromTo(someObject.transform.position, nextPoint.transform.position);
someObject.transform.SetParent(nextPoint.transform);
someObject.transform.localPosition = Vector3.zero;
if (!movingBack) someObject.State = nextPoint.SomeObjectState;
}
}
And Coroutine for moving from point A to point B:
IEnumerator MoveFromTo(Vector3 from, Vector3 to, float speed = 1f) {
while (Vector3.Distance(someObject.transform.position, to) > 0.01f) {
someObject.transform.position = Vector3.MoveTowards(someObject.transform.position, to, speed * Time.fixedDeltaTime);
yield return new WaitForFixedUpdate();
}
}
What am I doing wrong? It seems that "Move" Coroutine starting to work bewore "MoveFromTo" finishes and two "MoveFromTwo" Coroutines trying to work at same time, so someObject stops.
Comment