Set limits for the position of the Cinemachine camera that follows the player

I have a player object than can fall into the abyss. Player can move in any direction. Camera settings :

Camera follows player along all axes. But I need that when the player falls into the abyss, the camera remains in its Y position. That is, I need to set the minimum Y position for the cinemachine camera.

You can do that with a simple custom Cinemachine extension. Here is one that locks the vcam’s Y position to a fixed value. You can modify it to implement a minimum Y instead.

using UnityEngine;
using Cinemachine;

/// <summary>
/// An add-on module for Cinemachine Virtual Camera that locks the camera's Y co-ordinate
/// </summary>
[SaveDuringPlay] [AddComponentMenu("")] // Hide in menu
public class LockCameraY : CinemachineExtension
{
    [Tooltip("Lock the camera's Y position to this value")]
    public float m_YPosition = 10;

    protected override void PostPipelineStageCallback(
        CinemachineVirtualCameraBase vcam,
        CinemachineCore.Stage stage, ref CameraState state, float deltaTime)
    {
        if (stage == CinemachineCore.Stage.Finalize)
        {
            var pos = state.RawPosition;
            pos.y = m_YPosition;
            state.RawPosition = pos;
        }
    }
}
3 Likes

Hi Gregoryl,
How can we set the minimum and maximum y value of cinemachine.
So that it only moves within a range say y1 - y2.

I am facing an issue when player falls as we cannot see what is visible below, this might solve the issue
https://stackoverflow.com/questions/69279505/unity2d-player-off-camera-on-falling-with-cinemachine

You would have to modify the above script to clamp to a range instead of locking to a specific value.

1 Like