How to Make an Interactive Camera using Cinemachine and C#
Cinemachine is a powerful tool in Unity that allows you to create dynamic camera shots and transitions in your game. In this tutorial, we will be using Cinemachine and C# to create an interactive camera that follows the player, with the ability to zoom in and out and rotate around the player.
Step 1: Setting up Cinemachine
The first step is to install Cinemachine in your Unity project. You can do this by opening the Package Manager and searching for Cinemachine. Once you have installed Cinemachine, you can create a new Virtual Camera by going to GameObject > Cinemachine > Virtual Camera.
Step 2: Follow the Player
To make the camera follow the player, you need to set the Follow property of the Virtual Camera to the player’s transform. You can do this by dragging and dropping the player object into the Follow property in the Inspector.
Step 3: Zoom in and out
To add zoom functionality to the camera, we will use the mouse scroll wheel. First, you need to add a CinemachineInputProvider component to your camera. You can do this by selecting your Virtual Camera and adding a component in the Inspector.
Next, you can add the following code to your script to handle the mouse scroll wheel input:
This code gets the input from the mouse scroll wheel and adjusts the Field of View property of the Virtual Camera based on the input.
Step 4: Rotate around the player
To add rotation functionality to the camera, we will use the mouse movement. First, you need to add a CinemachineFreeLook component to your camera. You can do this by selecting your Virtual Camera and adding a component in the Inspector.
Next, you can add the following code to your script to handle the mouse movement input:
This code gets the input from the mouse movement and adjusts the X-axis rotation of the CinemachineFreeLook component based on the input.
Step 5: Limit the camera movement
To prevent the camera from moving too far away from the player, you can add some limits to the camera movement. You can do this by adjusting the settings in the CinemachineFreeLook component. In the Inspector, you can adjust the Orbital X-axis Clamp and Orbital Y-axis Clamp properties to limit the camera movement.
This code sets the maximum and minimum vertical angle of the camera movement to 30 degrees and -30 degrees, respectively.
Conclusion
In this tutorial, we have shown how to create an interactive camera using Cinemachine and C# in Unity. We have covered how to make the camera follow the player, zoom in and out, and rotate around the player. By adding some limits to the camera movement, we have created a more polished and professional-looking camera system for our game.