The exercise here demonstrates a quick way to introduce a minor jerk upon a hit on the player, to the main camera using animation in Unity.
- Select the main camera in your game and go to the animation window.
- Create an idle animation by giving the position of choice.
- After saving the idle animation, create a new animation and give a name of choice that depicts a shakey effect.
- In this animation, begin with an idle position of the camera and after a few seconds, move left/right/up/down as needed and, move back to the idle position.
- Record the animation and save it.
- Head to the animator window where both animations shall be waiting for a transition configuration.
- Create a trigger/bool as per choice to enable the shakey animation.
- Make a transition from the idle animation to the shake animation.
- Add the trigger under the conditions for this transition by clicking on the arrow. Also, we would like to immediately trigger the animation and hence the exit time needs to be disabled and the transition duration should be 0.
- Make another transition from the shakey animation to the idle animation.
- Here, the “has exit time” should be enabled and the exit time should be 1 as the shake effect has to run through fully to be felt on screen.
So far the animation mechanism is in place. The next requirement is to get a handle on the main camera and enable the animation trigger using code.
The player records a hit and has the code addressing the damage penalty. Therefore, the player script shall take care of the task here.
- Declare a private variable of Animator type and get a reference to the “Main Camera”.
private Animator _shakeCamera;
shakeCamera = GameObject.Find("Main Camera").GetComponent<Animator>();
- Null check the reference and enable the trigger.
if (_shakeCamera != null)
That should do it :)
Here is the final result.
Thank you very much