Unity Recipes - Head Bob or Breathe

Here’s a handy Unity script that, when applied to a game object, will give the object a repetitive, but smooth upward and downward movement. This effect is often used to make a “head bob” or to make a player object look like it’s breathing; especially when it’s in idle state. This kind of effect can be achieved by animating the object before importing it (in a program like Blender, for example), but it can also be achieved with a sine wave function as provided by this script. The same or a similar script can also be used to make a main menu camera bob or to make lights breathe. Here it is:

using System.Collections; using System.Collections.Generic; using UnityEngine; public class Breathe : MonoBehaviour { Vector3 startPos; public float amplitude = 10f; public float period = 5f; protected void Start() { startPos = transform.position; } protected void Update() { float theta = Time.timeSinceLevelLoad / period; float distance = amplitude * Mathf.Sin(theta); transform.position = startPos + Vector3.up * distance; } }

After applying the script, you will need to adjust the float values for the amplitude and period to your liking.

References