Last active
September 26, 2024 07:16
-
-
Save ftvs/5822103 to your computer and use it in GitHub Desktop.
Simple camera shake effect for Unity3d, written in C#. Attach to your camera GameObject. To shake the camera, set shakeDuration to the number of seconds it should shake for. It will start shaking if it is enabled.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
public class CameraShake : MonoBehaviour | |
{ | |
// Transform of the camera to shake. Grabs the gameObject's transform | |
// if null. | |
public Transform camTransform; | |
// How long the object should shake for. | |
public float shakeDuration = 0f; | |
// Amplitude of the shake. A larger value shakes the camera harder. | |
public float shakeAmount = 0.7f; | |
public float decreaseFactor = 1.0f; | |
Vector3 originalPos; | |
void Awake() | |
{ | |
if (camTransform == null) | |
{ | |
camTransform = GetComponent(typeof(Transform)) as Transform; | |
} | |
} | |
void OnEnable() | |
{ | |
originalPos = camTransform.localPosition; | |
} | |
void Update() | |
{ | |
if (shakeDuration > 0) | |
{ | |
camTransform.localPosition = originalPos + Random.insideUnitSphere * shakeAmount; | |
shakeDuration -= Time.deltaTime * decreaseFactor; | |
} | |
else | |
{ | |
shakeDuration = 0f; | |
camTransform.localPosition = originalPos; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is my modification, I made it completely generic. Just copy paste on any object and you're good to go.
How it works:
Flaws: