How to make camera shake and also follow player?

Hey, I’m making a 2D rouge-like, top down game. I would like the camera to shake whenever The player get’s hit. And I did some coding and I got a pretty nice script. But whenever you move and the camera shakes, it just moves back to the middle. I would like the camera to follow the player and shake around. How can I achieve this affect? Here’s my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraShake : MonoBehaviour
{
     public IEnumerator Shake (float duration, float magnitude)
     {
         Vector3 originalPos = transform.localPosition;

         float elapsed = 0.0f;

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

            transform.position = new Vector3(x, y, originalPos.z);

            elapsed += Time.deltaTime;

            yield return null;
         }

         transform.localPosition = originalPos;
     }
}

If you put your object under a parent that sets the world position, you can offset the localPosition to give it shake and when your offset goes to zero your object will return to the neutral position. If you do that, your shake script should work (but originalPos should always be Vector3.zero).

Please don’t use random values to cause camera shake! Use a continuous function like perlin noise or sine to get smooth movement.

Here’s a script ShakeIn2D that can shake objects or camera as shown in these videos.