首页 > 解决方案 > 游戏对象来回旋转

问题描述

我正在为我的游戏制作一些草,它需要看起来像有风。所以我试图写一个脚本,但根本没有成功。脚本将类似于它旋转一点的地方,然后是另一种方式。只是来回。

public GameObject grass;

    private void FixedUpdate()
    {
        grass.transform.Rotate(transform.rotation.x, transform.rotation.y, 90f * Time.deltaTime, Space.Self);
    }

正如您在我的代码中看到的那样,它将永远围绕自身旋转。这就是我得到的。

标签: c#unity3d

解决方案


首先,您不想这样做FixedUpdateUpdate否则您会感到紧张不安。

然后你可以简单地定义你的两个目标旋转并Mathf.PingPong用作因子,Quaternion.Slerp以便在两个旋转之间来回插值:

public Vector3 eulerAngles1;
public Vector3 eulerAngles2;
// How long it takes to go from eulerAngles1 to eulerAngles2
public float duration;

Quaternion rotation1;
Quaternion rotation2;

private void Start()
{
    rotation1 = Quaternion.Euler(eulerAngles1);
    rotation2 = Quaternion.Euler(eulerAngles2);
}

private void Update()
{
    var factor = Marhf.PingPong(Time.time / duration, 1);
    // Optionally you can even add some ease-in and -out
    factor = Mathf.SmoothStep(0, 1, factor);

    // Now interpolate between the two rotations on the current factor
    transform.rotation = Qiaternion.Slerp(rotation1, rotation2, factor);
}

推荐阅读