Search Unity

Resolved How to add a fading shake to my camera?

Discussion in 'Scripting' started by noobgenerator2000, Dec 16, 2022.

  1. noobgenerator2000

    noobgenerator2000

    Joined:
    Dec 4, 2022
    Posts:
    19
    I wrote code to make my camera shake on a trigger for a certain amount of time. Over time I want the shaking of the camera to slowly fade away so its more smooth and doesnt end abruptly, thanks!
    Code (CSharp):
    1. public IEnumerator Shake(float duration, float magnitude)
    2.     {
    3.         Vector3 originalPos = transform.localPosition;
    4.         float elapsed = 0.0f;
    5.         while (elapsed < duration)
    6.         {
    7.             float x = Random.Range(-1f, 1f) * magnitude;
    8.             float y = Random.Range(-1f, 1f) * magnitude;
    9.  
    10.             transform.localPosition = new Vector3(x, y, originalPos.z);
    11.  
    12.             elapsed += Time.deltaTime;
    13.  
    14.             yield return null;
    15.         }
    16.  
    17.         transform.localPosition = originalPos;
    18.  
    19.  
    20.     }
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,929
    A very basic idea could be to just linearly interpolate the values by getting inverse percentage of time elapsed and multiplying your x and y values by that:
    Code (CSharp):
    1. float p = 1f - (elapsed / duration);
    2. float x = Random.Range(-1f, 1f) * magnitude;
    3. float y = Random.Range(-1f, 1f) * magnitude;
    4.  
    5. x *= p;
    6. y *= p;
    Or you could use animation curves. Speaking of which... I would just use the Cinemachine package. It has features such as these built in.
     
  3. AnimalMan

    AnimalMan

    Joined:
    Apr 1, 2018
    Posts:
    1,164
    Did you try Lerping the value either side on the inside of the random range on a fade in and out timer?
     
  4. noobgenerator2000

    noobgenerator2000

    Joined:
    Dec 4, 2022
    Posts:
    19
    What is Cinemachine and how do I get it?
     
  5. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,929