How do I lock a certain axis when using a Cinemachine follow camera?

Hi everyone,

I’m trying to make a 2D platformer in Unity and I want the camera to only follow the player on the Y-axis while keeping the X position of the camera fixed. I found a Cinemachine Extension on the forum that seemed to work perfectly at first, but when reloading the scene, it breaks. Instead of staying locked on X, the camera moves in the opposite direction than the player is moving when the player moves, going outside of its 2D Composite boundaries. And by the way my editor version in Unity Hub is 6000.0.37f1, I wasn’t sure which one to pick when making this post.

The Extension (https://discussions.unity.com/t/lock-an-axis-in-2d-vcam-follow-mode/691086/2):

using UnityEngine;
using Unity.Cinemachine;

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

    protected override void PostPipelineStageCallback(
        CinemachineVirtualCameraBase vcam,
        CinemachineCore.Stage stage, ref CameraState state, float deltaTime)
    {
        if (enabled && stage == CinemachineCore.Stage.Body)
        {
            var pos = state.RawPosition;
            pos.x = m_XPosition;
            state.RawPosition = pos;
        }
    }
}

I also tried setting “CinemachineCore.Stage.Body” to “CinemachineCore.Stage.Finalize” and many other variations of the code I found in the discussions. The only person I found with the same problem as me was nathanbmnt in this topic: Lock an Axis in 2d VCam Follow Mode. But unfortunately it didn’t have any solution. Any solution for this would be greatly appreciated as I’ve spent the past two days on this.

Thanks in advance!

What happens if you change the code to this:

        if (enabled && stage == CinemachineCore.Stage.Finalize)
        {
            var pos = state.GetCorrectedPosition();
            pos.x = m_XPosition;
            state.RawPosition = pos;
            state.PositionCorrection = Vector3.zero;
        }

Thank you so much! When changing the code to this, it works perfectly: when reopening Unity, reloading the scene and when building the game.

1 Like