Switching Cameras Based on Animation States in Cinemachine
Objective: To learn how to switch cameras based on the animation state.
A state driven camera will change its active virtual camera dependant on the state that the ‘Animated Target’ is in at the time. Given this understanding, this camera could be used to build some pretty cool unique views that are seamless, all without any code. E.g. If our player is currently idle, we might want to transition to a virtual camera that simply orbits around the player very slowly, or if the player is running, then we might want a 3rd person follow over their right shoulder, or if they are picking up a certain object we could use a virtual camera to zoom in on the object.
How to Setup the State Driven Camera
There are a few steps to getting this get setup so let’s dive into it:
- Create a new State Driven Cinemachine camera by going to the top tabs → Cinemachine → Create State Driven Camera.
- Make sure there is a game object in the scene which has an Animator component attached to it with an Animation Controller. For this example we are going to have 2 different states in the animator so we can switch between them.
- Assign the game object in step 2 to the field labelled ‘Animated Target’ in the CinemachineStateDrivenCamera component.
Now that we have done this, we are able to add the states from the attached player into the state box below by pressing the ‘+’ button and ‘New State’:
Make sure to now add the different states and their respective virtual cameras into the newly created fields.
The Wait field refers to how long the player has been in that state before the camera transitions to that virtual camera. E.g. If we set the wait time to 3 seconds, the player would need to be in the idle animation state for 3 seconds before switching virtual cameras.
Setting Up a Simple Animator with 2 States
This is the animator I have setup on the player with 2 different states. They have a transition between them each way with a bool triggering the change in states:
Setup Your Virtual Cameras for Their Purpose
Make sure to also adjust your cameras to your preferences.
For this example while the player is in an idle state, virtual camera 1 will be active and using the orbital transposer.
When we trigger the bool switch, it will change over to virtual camera 2 and it will be in a 3rd person follow camera mode.
Let’s Test it Out!
Cinemachine State Driven Camera