- Home /
Move an object through a set of positions
Hi,
I am trying to figure out how I can make an object move through a set of positions...
I have an object and a set of position, like 5 different positions, for example. So, I would like to do my object go from point 1 to point 2, from point 2 to point 3, from point 3 to point 4 and, finally, from point 4 to point 5, smoothly.
I read answers like this one http://answers.unity3d.com/questions/12859/move-an-object-through-a-set-of-positions.html and this one http://answers.unity3d.com/questions/14279/make-an-object-move-from-point-a-to-point-b-then-b.html, particularly. I've implemented this last one, but nothing happens. This is my code:
for(int i = 0; i < number_pos-1; i++)
{
StartCoroutine(moveB(positions[i], positions[i+1], 2.0f));
//StartCoroutine(moveA(positions[i], positions[i+1]);
}
}
IEnumerator moveA (Vector3 pointA, Vector3 pointB)
{
transform.position = Vector3.Lerp(pointA, pointB, Time.time * smooth);
yield break;
}
IEnumerator moveB (Vector3 pointA, Vector3 pointB, float time)
{
float i = 0.0f;
float rate = 1.0f/time;
while (i < 1.0) {
i += Time.deltaTime * rate;
transform.position = Vector3.Lerp(pointA, pointB, i);
yield break;
}
}
Thanks for any help!
Answer by paulaceccon · Oct 23, 2012 at 08:15 PM
Hi, I could do this with the code bellow:
IEnumerator Move()
{
for(int i = 0; i < number_pos; i ++)
{
currentPosition = i;
yield return new WaitForSeconds(1f);
}
}
void FixedUpdate()
{
if (currentPosition == -1)
{
return;
}
transform.position = Vector3.Lerp(transform.position, positions[currentPosition], Time.deltaTime * 10);
}
After this, following a friend tip, I start to "play" with AniMate (http://wiki.unity3d.com/index.php?title=AniMate) to do more complex animation via script. (:
Answer by whydoidoit · Oct 04, 2012 at 07:41 PM
You want to use
yield return null;
not yield break which just stops it immediately.
But you've also got a problem in the outer loop which should also be a coroutine and you should be doing
yield return StartCoroutine(moveB...
Thank you $$anonymous$$ike. I have to admit that I really don't understand the use of yield. I read this http://msdn.microsoft.com/en-us/library/9k7k7cf0(v=vs.80).aspx but I kind of noob in C#. But thanks a lot. It's not working as I expect, the object is moving in a strange way, but something is happening now. (:
Yeah - don't read that! Unity uses yield as part of it's coroutine system to say "I've done enough" - yield break is effectively STOP NOW AND DONT CO$$anonymous$$E BAC$$anonymous$$! This is Unity's overview of yield
Your answer
Follow this Question
Related Questions
ricreate Lerp function 2 Answers
Crash on loop using Lerp. 1 Answer
Lerp a Object along X and Z axis only. 3 Answers
2D Movement Problems 2 Answers
2d move to point script help 0 Answers