协程中的四元数旋转不能正常工作?

时间:2015-04-08 17:39:48

标签: unity3d quaternions coroutine

好吧,我试图让每次玩家按下“E”时,一个名为“pathblock”的对象顺时针旋转90度。玩家应该能够通过垃圾邮件发送垃圾邮件,并且该区块可以毫发失败地旋转360度。

我想看旋转动画,所以我将coroutine与slerp函数结合使用。如果按下E,则会在更新中调用协程。

//Rotates the selected pathblock by 90 degrees over a specified time. A coroutine is necessary to render each slerp() result per seperate frame
IEnumerator RotatePathblock()
{
    Debug.Log("Start rotation!");
    Quaternion start = Quaternion.Euler(new Vector3(pathblock.transform.rotation.x, pathblock.transform.rotation.y, pathblock.transform.rotation.z)); //Set start variable for Slerp(), the current rotation of the pathblock
    Quaternion end = Quaternion.Euler(new Vector3(start.x, start.y, start.z-90.0f));

    Debug.Log(string.Format("Target Angle: {0}", end.eulerAngles.z));


    float normalizationFactor = 1.0f / pathblockRotationTime; //We need to normalize time since slerp() works with values between 0-1; we can convert values by multiplying with this factor
    float timePassed = 0.0f; //Time passed since the start of the linear interpolation. Starting at 0, it increases until it reaches 1. All values are rendered.

    while(timePassed < 1.0f) //While the time passes is less than 1 (the maximum of a linear interpolation)
    {
        timePassed += Time.deltaTime * normalizationFactor; //Increase the timePassed with the time passed since the last frame; the time is first normalized
        pathblock.transform.rotation = Quaternion.Slerp(start, end, timePassed); //Set the pathblock rotation to a new value defined by linear interpolation
        yield return null; //Stop the function, finish Update() and return to this while loop; this will cause all slerp() values to render, resulting in a smooth animation
    }
}

按照预期,第一次按下将路径块旋转90度。 第二次按下将路径块设置回其原始旋转,并再次将其旋转90度。 这让我相信'start'变量永远不会改变,即使它在调用函数时应该将自己设置为新的pathblock.transform.rotation,从而获得新的旋转。

如果有人能看出什么是错的,我会很感激。 对我的代码,评论等的任何其他批评也将不胜感激!

1 个答案:

答案 0 :(得分:0)

  Quaternion start = Quaternion.Euler(new Vector3(pathblock.transform.rotation.x, pathblock.transform.rotation.y, pathblock.transform.rotation.z)); //Set start variable for Slerp(), the current rotation of the pathblock

应该是:

Quaternion start = Quaternion.Euler(new Vector3(pathblock.transform.eulerAngles.x, pathblock.transform.eulerAngles.y, pathblock.transform.eulerAngles.z)); //Set start variable for Slerp(), the current rotation of the pathblock