Following the Player with Cinemachine’s VirtualCamera! (2.5D Platformer)
A quick and easy way of getting a camera to follow the player is by simply dragging our Main Camera to the Player in the Hierarchy and making it a child object. This doesn’t exactly offer the smoothest results/much in the way of customisation (particularly as regards damping), but thankfully the Cinemachine package offers a neat alternative solution.
With the Cinemachine package installed, click the Cinemachine tab followed by ‘Create Virtual Camera’. Rotate the camera until you’re happy with where it’s facing (in the case of this 2.5D platformer -90 on the Y and 0 on the X and Z should do). Then drag your Player GameObject into the ‘Follow’ Transform variable on the VirtualCamera’s ‘CinemachineVirtualCamera’ component:
This is what will be handling the ‘follow’ behaviour we’re looking for.
Take a look a bit lower on this component and you should find a ‘Body’ dropdown. Open it up, and set the Follow Offset to be how you’d like it. This is what’ll be controlling the position of the camera in relation to the player. Take a look at your scene and check to see how your game is oriented; in my case, ‘Y’ is up and down, ‘X’ is in and out, and ‘Z’ is left and right. You’ll most likely want your left/right and up/down axes to be zeroed out, centering the camera on your player, but feel free to adjust these. The in/out axis is what’s likely to be of most interest to us in this: how close do you want the camera to be to your player/how much of the scene around them do you want the player to see? I settled on a value of 18 for my X axis, but this’ll likely vary depending on your preferences and the size of the assets in your game.
Lastly, we have the matter of damping. Changing these X, Y, and Z values will determine how closely and/or quickly the camera will follow your player. If you want the camera to relentlessly lock onto the player, you can zero all of these values out (but that would probably defeat the point of using Cinemachine follow rather than parenting the camera). I’m personally quite happy with just having 1 on on the X and Y.
For the finished setup I’m using for this virtual camera:
Do make sure you’ve still got your Main Camera active and in the scene, and with all of this finished you should have a working camera setup that’ll follow your player 😉