Unity3D: Camera Shake Effect (Script)

A simple camera shake for Unity3D combining positional and rotational movement, with intensity and decay tunable from the inspector.

There is a nice post from Michael Jasper's Web explaining how to create a camera shaking effect in Unity3D. The technique is straightforward, combining positional movement with rotational movement to simulate a shaking sensation for players. This version has been modified to allow variable adjustment through the inspector view.

Place this code in a file named cameraShake.js:

#pragma strict

var originPosition:Vector3;
var originRotation:Quaternion;

var shake_decay: float = 0.002;
var shake_intensity: float;
var coef_shake_intensity : float = 0.3f;

function Start () {

}

function Update(){
    if(shake_intensity > 0){
        transform.position = originPosition + Random.insideUnitSphere * shake_intensity;
        transform.rotation =  Quaternion(
                        originRotation.x + Random.Range(-shake_intensity,shake_intensity)*.2,
                        originRotation.y + Random.Range(-shake_intensity,shake_intensity)*.2,
                        originRotation.z + Random.Range(-shake_intensity,shake_intensity)*.2,
                        originRotation.w + Random.Range(-shake_intensity,shake_intensity)*.2);
        shake_intensity -= shake_decay;
    }
}

function Shake(){
    originPosition = transform.position;
    originRotation = transform.rotation;
    shake_intensity = coef_shake_intensity;
}

Key Variables

shake_intensity determines the initial intensity — how much position variance is allowed during the shaking effect.

shake_decay controls the amount shake_intensity decreases each update cycle, determining whether the shake is brief or prolonged.

Usage

Call the shake function whenever needed by inserting this in your trigger event:

var cam = GameObject.Find("Main Camera").GetComponent("cameraShake") as cameraShake;
cam.Shake();

An example shooter game demonstrates this effect: use arrow keys for direction and spacebar to shoot enemies — the camera shakes when enemies are destroyed.