- Home /
Why Dose not this work (IEnumerator)
Hi. I'm having trouble with my script. I am trying to make my object move from A to B in x amount (this case 4) seconds; But when I run my script the objects just flies away and the teleports to point B;
Please help
if (Input.GetKey(KeyCode.H))
{
StartCoroutine(Move(transform.position, HomePos.transform.position, 3.0f, this.gameObject.transform));
}
IEnumerator Move(Vector3 A, Vector3 B, float time, Transform target)
{
float speed = Vector3.Distance(A,B) / time;
Vector3 direction = (B - A).normalized;
target.position = A;
float elapsed = 0.0f;
while (elapsed < time)
{
elapsed += Time.deltaTime;
target.Translate(direction * speed * Time.deltaTime);
yield return true;
}
transform.position = B;
}
One issue is that you are using Input.Get$$anonymous$$ey() ins$$anonymous$$d of Input.Get$$anonymous$$eyDown(). Get$$anonymous$$ey() returns true for every frame it is held down, so you are getting multiple $$anonymous$$ove() coroutines launched even for a brief key down.
Answer by robertbu · Jan 08, 2014 at 06:31 PM
I might do it this way:
void Update() {
if (Input.GetKeyDown(KeyCode.H)) {
StartCoroutine(Move(HomePos.transform.position, 3.0f, gameObject.transform));
}
}
IEnumerator Move(Vector3 newPos, float time, Transform target) {
float speed = (target.position - newPos).magnitude / time;
while (target.position != newPos) {
transform.position = Vector3.MoveTowards (target.position, newPos, Time.deltaTime * speed);
yield return null;
}
}
Note I've eliminated the start position and just assume the current position is the start position.
That helped the movement but now when I am trying to move agan it will constantly try to move back to HomePos. Is it possible to make it stop moving after 3s?
I'm not sure what problem you are facing. The coroutine will quit when the object reaches the 'newPos' destination which will be in the specified amount of time. Show me the code you are using, and I can spot the problem. As a guess, I'd day you are repeatedly calling '$$anonymous$$ove' rather than calling it only once. There are other ways to solve this problem that don't involve coroutines that might be more flexible for you.
Your answer
![](https://koobas.hobune.stream/wayback/20220613125850im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Instantiate Particles, WaitForSeconds and continue 1 Answer
Execute IEnumerator In 1 Frame 4 Answers
Fire rate for gun script, c# (not u/s) 1 Answer
WWW Request runs in Editor but not in Webplayer 1 Answer
IEnumerator only called once 3 Answers