Enhanced camera shake with perlin noise

I watched the camera shake section of the Math for Game programmers video linked to in the resources and implemented it. It definitely feels a lot nicer.

    [Header("Perlin shake")]
    [SerializeField] bool useEnhancedCameraShake = true;
    [SerializeField] float shakeSpeedMultiplier = 1f;
    [SerializeField] float traumaReductionRate = 0f;
    private float trauma=0f;
    private float perlinSeed;
    

    Vector3 startPosition;
    Vector3 startRotation;
    int shakeIterationsRemaining = 0;
    private void Awake() {
        perlinSeed = Random.Range(0f,1f);
    }
    // Start is called before the first frame update
    void Start()
    {
        startPosition = transform.position;
        startRotation = transform.rotation.eulerAngles;
        
    }

    void Update() 
    {
        if(useEnhancedCameraShake && trauma>float.Epsilon)
        {
            Execute();
        }
    }

    public void AddTrauma(float amount)
    {
        trauma+=amount;
        trauma = Mathf.Clamp01(trauma);
    }

    void Execute()
    {
        Vector3 deltaPosition = new Vector2
        (
            Mathf.PerlinNoise(perlinSeed,Time.time * shakeSpeedMultiplier),
            Mathf.PerlinNoise(perlinSeed + 1,Time.time * shakeSpeedMultiplier) 
        );
        deltaPosition *= shakeMagnitude * trauma * trauma;
        float maxRotation = maxShakeAngle * trauma * trauma;
        float deltaRotation = Mathf.PerlinNoise(perlinSeed + 2,Time.time * shakeSpeedMultiplier) * maxRotation;
        deltaRotation -= maxRotation / 2f;
        transform.position = startPosition + deltaPosition;
        transform.rotation = Quaternion.AngleAxis(deltaRotation + startRotation.z, transform.forward);

        trauma -= Time.deltaTime * traumaReductionRate;

    }
1 Like

Privacy & Terms