Camera shake using cinemachine is changing the layers of overlapping objects. (2d)

I posted this in unity answers and got no responses sooo

An example of the layers changing is when the camera shakes, my gun goes infront of my player even though it was behind it before, and overlapping platforms change layer too, like the floor appeared infront of the wall before but during the shake sometimes it goes behind it. When the camera stops shaking, the layers are back to normal btw. Here’s my code:

using System.Threading;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
public class CameraShake : MonoBehaviour
{
    public static CameraShake Instance { get; private set;}
    private CinemachineVirtualCamera cam;
    private float shakeTimer;
    void Awake()
    {
        Instance = this;
        cam = GetComponent<CinemachineVirtualCamera>();
    }
    public void Shake(float intensity, float time){
        CinemachineBasicMultiChannelPerlin camPerlin = cam.GetCinemachineComponent<CinemachineBasicMultiChannelPerlin>();
        camPerlin.m_AmplitudeGain = intensity;
        shakeTimer = time;
    }

    private void Update()
    {
        if(shakeTimer>0){
            shakeTimer -= Time.deltaTime;
            if (shakeTimer <=0f){
                CinemachineBasicMultiChannelPerlin camPerlin = cam.GetCinemachineComponent<CinemachineBasicMultiChannelPerlin>();
                camPerlin.m_AmplitudeGain = 0f;
            }
        }
    }
}

I didn’t use the shake extension for cinemachine btw

This is almost certainly a result of ambiguous layering (eg, two sprites on the same layer / group) than anything to do with the camera.

Check the sorting order of your sprites. Here’s some more reading:

Three (3) primary ways that Unity draws / stacks / sorts / layers / overlays stuff:

In short,

  1. The default 3D Renderers draw stuff according to Z depth - distance from camera.

  2. SpriteRenderers draw according to their Sorting Layer and Sorting Depth properties

  3. UI Canvas Renderers draw in linear transform sequence, like a stack of papers

If you find that you need to mix and match items using these different ways of rendering, and have them appear in ways they are not initially designed for, you need to:

  • identify what you are using
  • search online for the combination of things you are doing and how to to achieve what you want.

There may be more than one solution to try.

Additional reading in the official docs:

And SortingGroups can also be extremely helpful in certain circumstances:

1 Like