[2D] Overshooting camera and back to max position

Hi,

I am making a 2D platformer game and using the following camera extension to restrict the player’s movement beyond the level edges.

using UnityEngine;
using Cinemachine;

[ExecuteInEditMode] [SaveDuringPlay] [AddComponentMenu("")] // Hide in menu
public class CinemachineLockAxis2D : CinemachineExtension
{

    private float maxWidth;
    private float maxHeight;

    public void SetMaxBounds(float width, float height)
    {
        maxWidth = width;
        maxHeight = height;
    }
    protected override void PostPipelineStageCallback(
        CinemachineVirtualCameraBase vcam,
        CinemachineCore.Stage stage, ref CameraState state, float deltaTime)
    {
        if (enabled && stage == CinemachineCore.Stage.Body)
        {
            Vector3 pos = state.RawPosition;
            pos.x = Mathf.Clamp(pos.x, 0f, maxWidth);
            pos.y = Mathf.Clamp(pos.y, 0f, maxHeight);
            state.RawPosition = pos;
        }
    }
}

Right now, the camera follows the player but stops abruptly when it reaches the edge.

My question, is it possible to make it stop smoothly, overshoot a little and then move it back to the maximum position?
Just like when scrolling a list view on mobile devices… it overshoots and then comes back to the maximum position.

Any leads would be great. Thank you

Why don’t you use the CinemachineConfiner extension, and give it some damping?

The camera movement is very odd if I lock X or Y axis… even though the bounds are greater than the camera size

If I set pos.x or pos.y to zero… the camera still moves… I guess its because the confiner is modifying the value?

        if (enabled && stage == CinemachineCore.Stage.Body)
        {
            Vector3 pos = state.RawPosition;
            pos.x = lockX ? 0 : pos.x;
            pos.y = lockY ? 0 : pos.y;
            state.RawPosition = pos;
        }

I used this script which you posted here.
https://discussions.unity.com/t/691086

Well, then perhaps you can get inspired by the code in Confiner, and add damping in that manner.

1 Like

Yup seems like it :slight_smile: