C# script to make camera shake.


Content not available.
Please allow cookies by clicking Accept on the banner

Simply attach this script to the camera you are using. It should work in 3D and 2D mode, in 2D simply set axisShakeMin.z and axisShakeMax.z to 0.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

// ? 2017 TheFlyingKeyboard and released under MIT License
// theflyingkeyboard.net

public class CameraShake : MonoBehaviour {
    public Vector3 axisShakeMin;
    public Vector3 axisShakeMax;

    public float timeOfShake;
    private float timeOfShakeStore;

    private bool shake;
    private Vector3 startPos;

    // Use this for initialization
    void Start () {
        shake = false;
        startPos = transform.position;

        timeOfShakeStore = timeOfShake;
  // Update is called once per frame
  void FixedUpdate () {
        if (shake)
            transform.position = startPos + new Vector3(Random.Range(axisShakeMin.x, axisShakeMax.x), Random.Range(axisShakeMin.y, axisShakeMax.y), Random.Range(axisShakeMin.z, axisShakeMax.z));

            timeOfShake -= Time.deltaTime;

            if (timeOfShake <= 0.0f)
                shake = false;

                transform.position = startPos;

    public void ShakeCamera(float shakeTime = -1.0f)
        if (shakeTime > 0.0f)
            timeOfShake = shakeTime;
            timeOfShake = timeOfShakeStore;

        shake = true;


Unity C# Camera Shake
Tagged on:     

Leave a Reply

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. You can read more about it the Cookies&Privacy Policy Section Above. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this. You can read more about it the Cookies&Privacy Policy Section.