Shaking Transform - edcasillas/unity-common-utils GitHub Wiki

A component to add shaking capabilities to any Transform, inspired by this amazing tutorial: https://roystan.net/articles/camera-shake.html

The most common use case for this component is to create shaking camera effects, but it can also be used to create shaking effects for any other kind of game object, even UI components.

Please note it's important that the Game Object with the ShakingTransform component is a child of another one in order to preserve the original position and rotation after shaking. Also, in the case of RectTransforms, it's important that parent's anchors are center/middle and the pivot is at the center (0.5, 0.5).

Shaking Transform Presets

Shaking Transforms make use of presets for easier configuration. A shaking transform preset defines how the transform is going to shake through the following parameters:

  • Intensity: Defines the maximum translation at each axis.
  • Angular Intensity: Defines the maximum rotation at each axis.
  • Frequency: How fast is the shake?
  • Recovery Speed: How fast will the shake stop? The higher the value, the faster it stops.
  • Magnitude: Multiplier to control the smooth falloff of the shake.

To create a preset, right-click anywhere in the Project view and select Create->Common Utils->Shaking Transform Preset. Once the values are tweaked, you can assign presets to shaking transforms through the inspector.

Induce Stress

To start shaking the transform, call the InduceStress method of the ShakingTransform component.

The InduceStress method has two overloads:

  • The first one accepts a preset name as a string parameter. This is meant to be used when the preset has been assigned via the Inspector to the ShakingTransform component.
  • The second one accepts a preset itself as a parameter. This one is meant to be used when you have manually configured your presets somewhere else in your code.

Both overloads receive an optional stress parameter. You will usually use a value of 1 for this parameter, but you can also use it to control how much the shake increases each time stress is induced. A good example is creating a shaking effect out of an explosion in the game: you want a more dramatic shake the closer the ShakingTransform is to the explosion, so you would send stress = 1 when the ShakingTransform is too close, or decrease this value the farther it is. For this specific example, which is a very common use case, there's the special method InduceExplosionStress, which you can use out-of-the-box.

Demo Scene and Examples of Usage

Included with the Common Utils package, there's a demo scene inside Demos/Effects/ShakingTransform.

The demo scene includes a camera and a button using the ShakingTransform component. To test them, enter Play mode and click either the camera or the button in the Hierarchy view. The inspector will show it's debug values, and you'll be allowed to test different presets to make them shake.