The Art of Screenshake (with Unity 2D script)
This is a great presentation by Jan Willem Nijman of Dutch dynamic duo Vlambeer. He talks about crafting the feedback that your player receives when playing your game, including things like screenshake, camera movement and explosions. There are some very useful ideas in here. I put together a simple unity script aimed at Unity 2D which implements screenshake by moving the camera on collision which was inspired by this, grab it below.
To use this script:
- Assets > Create > C# Script
- Name the new script “CamShakeSimple” (as in the class name)
- Add CamShakeSimple to the game object that will cause the shake, in this case it’s setup to shake the camera when this 2D object collides with something.
- Drag your main camera into the newly visible slot in the inspector called “Main Camera”
- Now when this object hits another it will use the relative velocity of that collision to shake the camera. Other ideas might include shaking the cam when you fire a bullet, fall from high up, or any number of things.
- Note that if you’re using this in 3D you’ll want to remove the two instances of “2D” from the collision portion.
using UnityEngine; using System.Collections; public class CamShakeSimple : MonoBehaviour { Vector3 originalCameraPosition; float shakeAmt = 0; public Camera mainCamera; void OnCollisionEnter2D(Collision2D coll) { shakeAmt = coll.relativeVelocity.magnitude * .0025f; InvokeRepeating("CameraShake", 0, .01f); Invoke("StopShaking", 0.3f); } void CameraShake() { if(shakeAmt>0) { float quakeAmt = Random.value*shakeAmt*2 - shakeAmt; Vector3 pp = mainCamera.transform.position; pp.y+= quakeAmt; // can also add to x and/or z mainCamera.transform.position = pp; } } void StopShaking() { CancelInvoke("CameraShake"); mainCamera.transform.position = originalCameraPosition; } }
To give credit where it’s due, this is a combination of code fragments from this thread:
http://answers.unity3d.com/questions/220407/damaging-a-car-depending-on-force-of-impact.html
and this one:
http://answers.unity3d.com/questions/46317/screen-shake-effect.html?sort=oldest