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;
}
}