项目需要一个简单的摄像机抖动效果,于是顺手写了一个协程版本的实现。思路是记下摄像机的初始位置,在短时间内反复给它加上一个随机偏移,结束后再把位置还原。

实现代码

下面这段 C# 协程通过 WaitForSeconds 以 0.01 秒为步长连续扰动 20 次,X 轴使用较大的随机幅度,Y 轴则控制在较小范围内,最后把摄像机位置恢复到起始点。

  IEnumerator shakeCamera()
    {

        Vector3 pos_orign = GetComponentInChildren<Camera>().GetComponent<Transform>().position;

        for (int i = 0; i < 20; i++)
        {
            yield return new WaitForSeconds(0.01f);
            Vector3 pos = GetComponentInChildren<Camera>().GetComponent<Transform>().position;

            pos.x = pos_orign.x+ Random.Range(-1.0f, 1.0f);
            pos.y = pos_orign.y+ Random.Range(-0.1f, 0.1f);
         //   pos.z += Random.Range(-10, 10);

            GetComponentInChildren<Camera>().GetComponent<Transform>().position=pos;

        }
        GetComponentInChildren<Camera>().GetComponent<Transform>().position = pos_orign;

    }