Make camera shake whilst it is animated

I’m making a side scrolling game but i’ve set up the camera using animation to give it a more cinematic feel, the problem is I had a script setup to shake the screen if the player took damage and now im using the animator the screen shake doesn’t work. Is there any way to implement the shake without temporarily disabling the animator component? My shake script:

using UnityEngine;
using System.Collections;

public class CameraShake : MonoBehaviour
{
    public static CameraShake instance;


private Vector3 _originalPos;
private float _timeAtCurrentFrame;
private float _timeAtLastFrame;
private float _fakeDelta;

void Awake()
{
    instance = this;
}

void Update()
{
    // Calculate a fake delta time, so we can Shake while game is paused.
    _timeAtCurrentFrame = Time.realtimeSinceStartup;
    _fakeDelta = _timeAtCurrentFrame - _timeAtLastFrame;
    _timeAtLastFrame = _timeAtCurrentFrame;
}

public static void Shake(float duration, float amount)
{
    instance._originalPos = instance.gameObject.transform.localPosition;
    instance.StopAllCoroutines();
    instance.StartCoroutine(instance.cShake(duration, amount));
}

public IEnumerator cShake(float duration, float amount)
{
    float endTime = Time.time + duration;

    while (duration > 0)
    {
        transform.localPosition = _originalPos + Random.insideUnitSphere * amount;

        duration -= _fakeDelta;

        yield return null;
    }

    transform.localPosition = _originalPos;
}
}

You should be able to manually transform an animated object by updating it within the LateUpdate() method. Keep in mind that the camera will keep snapping back to the current animation position prior to late update, so you’ll have to have some variables to handle smoothly transitioning between camera states.

Let me know if that works for you.

You could consider making the camera the child of another GameObject. Animate the parent object, which obviously moves the child with it, and shake the child which is the actual camera using local coordinates. Both the animation and the shake would then be able to happen at the same time independently, without interfering with each other.

1 Like