Camera Shake Effect When Camera Following Player

I was working on a 3d game where the camera is continuously following the player object.
Now when a bomb hits the player object I want to play camera shake with blast particle effect.

I have coded this for camera shake:

public IEnumerator PlayCameraShakeAnimation(float duration, float magnitude)
    {
        Vector3 originalPosition = transform.localPosition;
        float elapsedTime = 0f;

        while(elapsedTime < duration)
        {
            float x = Random.Range(-1f, 1f) * magnitude;
            float y = Random.Range(-1f, 1f) * magnitude;

            transform.localPosition = new Vector3(x, y,originalPosition.z);
            elapsedTime += Time.deltaTime;

            yield return null;
        }

        transform.localPosition = originalPosition;
    }

Camera Follow is the normal script I have written to follow the player.
Because of Camera Follow script is running, camera shake effect we can’t able to show in the screen.

If I turn off Camera Follow script then we can able to see clearly camera shaking otherwise not.

If I turn off Camera Follow script for a small amount of time then I am losing smoothness in following of player because the player position gets updated after the blast. So when I start back following the player, it will get a high jerk in a movement to reach a target position.

Also, the Camera is following the player in position and rotation in both fields. Now provide me some suggestions to achieve the Camera Shake effect while following the player.

Right now the Camera GameObject is just a single GameObject, correct? Change it so the camera is two GameObjects, the main GameObject which has the scripts attached and does the following of the player, and a child GameObject which actually has the camera attached. When you follow the player you move that main parent GameObject. When you do your camera shake effect you shake the child in local space (which again actually has the camera component attached).

Doing it like that makes the shake effect and the camera follow movement entirely independent from each other.

2 Likes