How to make the camera shake in unity?

In this article, I will show you How to make a camera shake in unity through C#. This is how our camera shake will be looking like in unity.

So if you want something similar to this then you continue reading it and get your solution quickly.

Camera shake in unity

For Creating camera shake in unity first, We will create a C# script for camera shake and you can give a name according to your preference, In my case, I gave it the name CameraShake.cs. Then just copy and paste the code I shared below and don’t forget to change the scripts name if you have a different script name from me. This is a very simple camera shake script.

using UnityEngine;

public class CameraShake : MonoBehaviour
{
    // Camera Information
    public Transform cameraTransform;
    private Vector3 orignalCameraPos;

    // Shake Parameters
    public float shakeDuration = 2f;
    public float shakeAmount = 0.7f;

    private bool canShake = false;
    private float _shakeTimer;

 

    // Start is called before the first frame update
    void Start()
    {
        orignalCameraPos = cameraTransform.localPosition;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            ShakeCamera();
        }

        if (canShake)
        {
            StartCameraShakeEffect();
        }
    }

    public void ShakeCamera()
    {
        canShake = true;
        _shakeTimer = shakeDuration;
    }

    public void StartCameraShakeEffect()
    {
        if (_shakeTimer > 0)
        {
            cameraTransform.localPosition = orignalCameraPos + Random.insideUnitSphere * shakeAmount;
            _shakeTimer -= Time.deltaTime;
        }
        else
        {
            _shakeTimer = 0f;
            cameraTransform.position = orignalCameraPos;
            canShake = false;
        }
    }

}

Attach this script to your GameManager game object in the hierarchy.

 

Explanation

There are only 2 main variables:-

shakeDuration:- This is the duration that how long your camera shake will be, So if you want to increase/decrease the time of shake, Simply change the shake duration according to your requirements.

shakeAmount:- This parameter will define how long your how hard your shake will be so if you want to increase/decrease the amount of shake just simply play with this variable

Conclusion

And that concludes the basics of how to make a camera shake in unity and hope that this will be helpful while you work with Unity3D. Hopefully, you found it informative. Feel free to leave some feedback. Thank you.

Hope it was helpful, Let me know if you have any other issues or queries you can contact me through social media.

 

You can also find my youtube video on the same topic

Leave a Comment

Your email address will not be published.