简体   繁体   English

协程只执行一次

[英]coroutine executes only once

I have a game where a car moves on a road, which has triggers along it.我有一个游戏,汽车在路上行驶,路上有触发器。 The purpose is to detect when the car enters those triggers and to do stuff depending on the trigger.目的是检测汽车何时进入这些触发器并根据触发器执行操作。

For the one I am having trouble, the camera is supposed to slowly move towards a second position which is behind and slightly above the car.对于我遇到问题的那个,相机应该慢慢地移向第二个 position,它位于汽车后面并略高于汽车。

Here is what I tried:这是我尝试过的:

    private void OnTriggerEnter(Collider other)
{


    if (other.attachedRigidbody.velocity.magnitude > 20.0f)
    {
        StartCoroutine(tst());
    }

}
IEnumerator tst()
{
    Camera cam = Camera.main;
    Vector3 newPosition = cam.gameObject.transform.GetChild(0).position;
    cam.transform.position = Vector3.MoveTowards(cam.transform.position, newPosition, camUnit);

    yield return new WaitForSeconds(3);

}

The camUnit is equal 1f but the problem is that it doesn't move to the correct location, as in if I just assign it the new position the camera is in a different perspective than the code above and it is instant and not slow to move to the next position. camUnit 等于 1f 但问题是它没有移动到正确的位置,就像我只是将新的 position 分配给它一样,相机的视角与上面的代码不同,而且它是即时的,移动并不慢到下一个 position。

What am I doing wrong?我究竟做错了什么? Thank you in advance.先感谢您。

Directly after your yield you are exiting the Coroutine.在您的yield之后,您将立即退出协程。 With what you describe, you actually want this in some form of loop, and yield after doing what you need to do.根据您的描述,您实际上希望以某种形式的循环,并在完成您需要做的事情后yield Then, after the function resumes you decide whether you go again and yield again, or continue on towards the exit of the Coroutine.然后,在 function 恢复后,您决定是再次 go 并再次让步,还是继续朝着协程的出口前进。

    bool isDone = false;
    while(!isDone)
    {
        Camera cam = Camera.main;
        Vector3 newPosition = cam.gameObject.transform.GetChild(0).position;
        cam.transform.position = Vector3.MoveTowards(cam.transform.position, newPosition, camUnit);

        yield return new WaitForSeconds(3);
        isDone = EnsureCameraLocation(); // Do whatever check you need to do to figure out if the camera is where you want it yet
    }

Note that the yield is inside the while statement which is what will make the Coroutine seamless.请注意, yieldwhile语句中,这将使协程无缝。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM