从一边到另一边倾斜游戏对象

时间:2016-03-31 12:30:15

标签: c# unity3d rotation

我正在玩Google Cardboard。我坐在驾驶舱内,我可以毫无问题地环顾四周。

现在我想将驾驶舱从一侧倾斜到另一侧,以提供更逼真的感觉,而不仅仅是静止。

到目前为止,我有这个:

using UnityEngine;
using System.Collections;

public class Tilt : MonoBehaviour 
{
    float speed = 0.25f;

    void Update()
    {
        Tilter ();
    }

    void Tilter()
    {
        if (transform.rotation.z < 5f) {
            transform.Rotate (new Vector3 (0f, 0f, speed));
        }

        if (transform.rotation.z > 5f)
            transform.Rotate (new Vector3 (0f, 0f, -speed));
    }

}

这开始按预期向左倾斜驾驶舱,但是一旦旋转变得大于5的值,驾驶舱不会以另一种方式旋转,它会以相同的方式继续旋转,而不是相反的方向。

1 个答案:

答案 0 :(得分:2)

我没有尝试过这段代码,但是如果我明白你要做什么,我建议使用Mathf.Sin和Time.time来连续获取-1到1范围内的值,然后乘以旋转驾驶舱的范围。例如:

using UnityEngine;
using System.Collections;

public class Tilt : MonoBehaviour 
{
    float speed = 1.0f;
    float rotationAngle = 45;

    void Update()
    {
        Tilter ();
    }

    void Tilter()
    {
        float rotationZ = rotationAngle * Mathf.Sin(Time.time * speed);
        transform.Rotate (new Vector3 (0f, 0f, rotationZ ));
    }

}

这个例子应该慢慢将你的驾驶舱从0旋转到45,然后再回到0,然后回到-45,然后回到0,依此类推(再次我没试过)。

您可以增加或减少速度值,以使旋转更快或更慢。

相关问题