Help with making a camera shake coroutine

IEnumerator ShakeCoroutine(float shakeAmount, float fadeInTime, float length, float fadeOutTime)
    {
        float time = 0;
        while (time < fadeInTime)
        {
            float t = time / fadeInTime;
            shake = Mathf.Lerp(0, shakeAmount, t);
            time += Time.deltaTime;
            yield return new WaitForEndOfFrame();
        }
        yield return new WaitForSeconds(length);
        time = 0;
        while (time < fadeOutTime)
        {
            float t = time / fadeInTime;
            shake = Mathf.Lerp(0, shakeAmount, 1 - t);
            time += Time.deltaTime;
            yield return new WaitForEndOfFrame();
        }
    }

Trying to make a camera shake coroutine using 4 variables: shakeAmount, fadeInTime, length and fadeOutTime. I want the coroutine to increase shake by shakeAmount over the fadeInTime, wait for length, then decrease shake by shakeAmount over fadeOutTime. I also need it to function if fadeInTime, length or fadeOutTime are set to 0. I’ve been trying a couple methods for a while and can’t quite get it to work. If anyone has any ideas or a similar script they can share it would be much appreciated

we figured it out, we had the wrong variable on line 16! fadeInTime should be fadeOutTime. the working script now looks like this:

IEnumerator ShakeCoroutine(float shakeAmount, float fadeInTime, float length, float fadeOutTime)
    {
        float time = 0;
        while (time < fadeInTime)
        {
            float t = time / fadeInTime;
            shake = Mathf.Lerp(0, shakeAmount, t);
            time += Time.deltaTime;
            yield return new WaitForEndOfFrame();
        }
        yield return new WaitForSeconds(length);
        time = 0;
        while (time < fadeOutTime)
        {
            float t = time / fadeInTime;
            shake = Mathf.Lerp(0, shakeAmount, 1 - t);
            time += Time.deltaTime;
            yield return new WaitForEndOfFrame();
        }
    }
1 Like

I’m glad you’re moving and shaking again, but for future shakers, just know Cinemachine already supports shaking:

2 Likes

Or your favorite tweening package.

1 Like