How to Create Simple Screen Shake
Shake Shake Shake
Today we add an screen shake effect when the Player is hit.
Setup
Create a script: ShakeBehaviour
Attach to Camera
Create Shake Effect
We will be using the Random.insideUnitSphere function. As stated in the documentation: “Returns a random point inside or on a sphere with radius 1.0".
First we store the initial position of the camera. We’ll use this to return to the initial position again. That’s why it’s set in Start(). Next we use the Random.insideUnitSphere to move the camera around. By adding the random value to the initial position. With the magnitude multiplier we can adjust to create an bigger shake or smaller one.
Start Shaking
When shakeduration is positive we start the screen shake. Create a public method to set the shakeduration value so the shaking starts.
End Shaking
To end the shake we use Time.deltaTime multiplied by a dampingSpeed value. This will decrease the duration of the shake over time till it hits zero or below. Then the shaking will end till shakeduration becomes greater then 0 again.
Code Screen Shake
public class ShakeBehaviour : MonoBehaviour
{
[SerializeField] private float _shakeDuration;
[SerializeField] private float _shakeMagnitude = 0.08f;
[SerializeField] private float _dampingSpeed = 3f;
private Vector3 _initialPos;
// Start is called before the first frame update
void Start()
{
_initialPos = transform.position;
}
// Update is called once per frame
void Update()
{
if (_shakeDuration > 0)
{
transform.position = _initialPos + Random.insideUnitSphere * _shakeMagnitude;
_shakeDuration -= Time.deltaTime * _dampingSpeed;
}
else
{
transform.position = _initialPos;
}
}
public void CameraShake()
{
_shakeDuration = 2f;
}
}
Final Result: Subtle Shake on Player Hit
Play around with the number till you have the desired look.
There will be other methods for sure, but this one is quite simple.