Basic 2D “Screen Shake” in Unity
Like this post? You might like BentoBlox too — check out the game here on the App Store.
In 2D gaming, a screen shake effect tied to movements on screen can give important sensory feedback to the player.
In Unity, it’s simple to implement. Here’s one way to do it (in the meantime if you want to look through the finished script, you can find it here):
Create a new script (Create > C# Script
).
Call itShakeBehavior
and attach it to your scene’s camera GameObject
.
In ShakeBehavior
, add a few variables:
// Transform of the GameObject you want to shake
private Transform transform;
// Desired duration of the shake effect
private float shakeDuration = 0f;
// A measure of magnitude for the shake. Tweak based on your preference
private float shakeMagnitude = 0.7f;
// A measure of how quickly the shake effect should evaporate
private float dampingSpeed = 1.0f;
// The initial position of the GameObject
Vector3 initialPosition;
Now, in Awake
, store your camera’s transform:
void Awake()
{
if (transform == null)
{
transform = GetComponent(typeof(Transform)) as Transform;
}
}
Next, in OnEnable
, store the initial position of your camera’sGameObject
:
void OnEnable()
{
initialPosition = transform.localPosition;
}
Put the logic for the “shake” effect in Update
or FixedUpdate
, either is fine.
The logic is simple. If shakeDuration
is positive, adjust the game object’s transform by a random factor (that’s our shake). Decrement shakeDuration
so that your camera doesn’t shake forever. Once shakeDuration
reaches 0
, return your camera’s GameObject
to its initial position:
void Update()
{
if (shakeDuration > 0)
{
transform.localPosition = initialPosition + Random.insideUnitSphere * shakeMagnitude;
shakeDuration -= Time.deltaTime * dampingSpeed;
}
else
{
shakeDuration = 0f;
transform.localPosition = initialPosition;
}
}
It’s that easy. One final thing you can do is expose a function to the editor that allows you to wire up an event (such as an avatar bumping into a wall or hitting the ground after a glorious jump), to your shake effect:
public void TriggerShake() {
shakeDuration = 2.0f;
}
With that in place, shaking the camera is as simple as adding a reference to a GameObject
containing ShakeBehavior
and calling TriggerShake()
on it.
Like this post? You might like BentoBlox too — check out the game here on the App Store.