Prevent the Camera View Being Blocked by Obstacles - Unity Game Development Tutorial
In this Unity game development tutorial we're going to look at how we can configure our camera, so that it automatically adjusts the view when the line of sight to our character is blocked.
You can either watch the video version below or continue reading for written instructions.
OK, we'll start with this scene that has a character and some obstacles.
We've currently got a Cinemachine virtual camera that follows the character around, but at the moment, if we move behind the wall, our view is blocked.
We're now going to use another component of Cinemachine to prevent the view from being blocked. We'll click on the Extensions dropdown and select Cinemachine Collider.
This adds a component that will check if the view to the target is blocked and will automatically try to resolve it.
There are a few strategies for how it tries to do this.
The default strategy is 'Preserve Camera Height', which will attempt to change the view while staying at the original height.
Alternative options are 'Pull Camera Forward', which moves the camera forwards along the Z axis, and 'Preserve Camera Distance', which changes the view while trying to maintain the original distance from the target.
We'll leave the default settings and press play to try it out. Now when we move behind the wall, the camera rotates to keep the character in view.
And if we move away from the wall, the camera returns to its original position.
At the moment, the camera snaps instantly between the different views. We can make this look a lot smoother by adding some damping to the movement.
Let's stop the game and set the Damping value to 2. This setting determines how quickly the camera will return to its normal position. We'll also set the 'Damping when Occluded' value to 2. This setting determines how quickly the camera will move when trying to resolve an occlusion.
Let's press play to try this out. Now when we move behind the wall, the camera moves smoothly to keep the character in view.
And when we move away from the wall, the camera smoothly returns to the original position.
That covers everything for this tutorial. We hope that you found it useful. Please leave any questions or feedback in the comments below, and don't forget to subscribe to get notified when we publish our next post.
Post a Comment