简体   繁体   English

Unity 5对象平移和旋转

[英]Unity 5 Object translation and rotation

I am having an issue in unity where my object will do a translation and then nothing else, I want a sequence of translations and rotations to occur but it only does the first translation in the code and wont stop, I tried using a separate function to execute the translation instead of the Update function but this didn't work either, please help. 我在统一方面遇到问题,我的对象将执行翻译,然后再执行其他操作,我希望发生一系列翻译和旋转,但是它仅执行代码中的第一个翻译,并且不会停止,我尝试使用单独的函数来执行翻译而不是执行Update函数,但这也不起作用,请提供帮助。

void Update () 
{
    if (enemyHit == false)
    {
        //enemy moving
        transform.LookAt(TTarget);


    }
    else if (enemyHit == true)
    {
        Debug.Log (enemyHit);

        Evade();
    }
}

IEnumerator Wait(float duration)
{
    yield return new WaitForSeconds(duration);
}

void Evade()
{
    transform.Translate(Vector3.back * Time.deltaTime * movementSpeed);
    Wait(2);
    transform.Rotate(0,90,0);



}

A coroutine function should not be called directly like a normal function. 协程函数不应像普通函数一样直接调用。 You must use StartCoroutine to call it. 您必须使用StartCoroutine来调用它。

void Evade()
{
    transform.Translate(Vector3.back * Time.deltaTime * movementSpeed);
    StartCoroutine(Wait(2););
    transform.Rotate(0,90,0);
}

Even when you fix that, the rotae function will now be called but there will be no waiting for 2 seconds. 即使您修复了该问题,现在仍将调用rotae函数,但无需等待2秒钟。 That's because a normal function does not and will not wait for coroutine function to return if the coroutine function has yield return null or yield return new WaitForSomething ..... 那是因为如果协程函数具有yield return nullyield return new WaitForSomething ...,那么普通函数不会也不会等待coroutine函数返回。

This is what you should do: 这是您应该做的:

You call a coroutine function when enemyHit is true . enemyHittrue时,您将调用协程函数。 Inside the coroutine function, you translate , wait then rotate . 在协程函数内部,您翻译等待然后旋转 I suggest you learn about coroutine and understand how it works before using it. 我建议您在使用协程之前了解一下协程。

void Update()
{
    if (enemyHit == false)
    {
        //enemy moving
        transform.LookAt(TTarget);


    }
    else if (enemyHit == true)
    {
        Debug.Log(enemyHit);
        StartCoroutine(Evade(2));
    }
}

IEnumerator Evade(float duration)
{
    transform.Translate(Vector3.back * Time.deltaTime * movementSpeed);
    yield return new WaitForSeconds(duration);
    transform.Rotate(0, 90, 0);
}

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

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