Prevent cam from panning out of playarea

I’m building a 2D game, where the entire play field is randomly generated. Thus, I do not know the dimensions and center-location of the playable area.
I’m using Cinemachine and a virtual camera to enable pan and zoom functionality.

Now, I need the camera to keep within the randomly generated playfield and I’m not entirely sure how to achieve that. Ideally, the camera would allow panning until the last pieces of the playable area are just about visible and then just stop panning at all, until the user changes panning direction.

I’ve tried using a Polygon Collider 2D as a camera boundary, but since the map might be very slim and tall, this boundary in some cases does not fit the view and thus spectacularly stops working at all.
My current approach is checking the “pan-drag” direction and distance on each frame, applying the transform to the cam, checking if any GameObject centers are in view and if not, restoring the previous camera position.
This, however, leads to some very nasty flickering, camera jumping back and forth all the time, camera getting “stuck” outside the playable area without being able to be moved back…

This is my current try, a script on the virtual camera object:

public class CamControl : MonoBehaviour {
    [Header("Attributes")]
    public float panMagnitudeThreshold = 1f; // this is used to allow clicks without detecting tiny movements
    public int panBoundaryOvershoot = 2; // margin to allow the camera to move a bit outside the bounds, currently unused

    private Vector3 touchStart; // cached position of last frame's touch position
    private Camera camMain;
    Vector3 viewPos; // position of object in viewport, used for visibility checking
    Vector3 currentCamPos; // cached position of camera
    private bool isCalculationPanning; // a flag, an attempt to stop the jumping and jittering behaviour

    private void Start() {
        camMain = Camera.main;
    }

    private void Update() {
        // cache position of first touch location to calculate direction and amount
        if (Input.GetMouseButtonDown(0)) touchStart = camMain.ScreenToWorldPoint(Input.mousePosition); 

        if (Input.GetMouseButton(0)) {
            if (isCalculationPanning) return; // see flag above
            Vector3 direction = touchStart - camMain.ScreenToWorldPoint(Input.mousePosition);
            touchStart = camMain.ScreenToWorldPoint(Input.mousePosition); // cache new touch position
            if (direction.magnitude < panMagnitudeThreshold) return; // see field comment
            isCalculationPanning = true; // see flag above
            currentCamPos = transform.position; // save current camera position in case it needs to be restored
            transform.position += direction; // apply pan

            // check if at least anything of the play field is still visible
            bool anyVisible = false; 
            foreach (GameObject tile in MapManager.Manager.plotTiles) {
                viewPos = camMain.WorldToViewportPoint(tile.transform.position);
                if (viewPos.x >= 0 && viewPos.x <= 1 && viewPos.y >= 0 && viewPos.y <= 1) {
                    anyVisible = true;
                    break;
                }
            }

            // if not, restore former camera position
            if (!anyVisible) transform.position = currentCamPos;
            isCalculationPanning = false; // lift flag
        }
    }
}

Have you tried using a CinemachineConfiner2D extension on the vcam? It’s designed to do exactly this.

Hi Gregoryl, yes, I’ve tried that (as stated, using a Polygon Collider 2D). But since the map might be extremely narrow for example, the collider often ends up being smaller than the current viewport (the camera starts zoomed out all the way to show the entire map). During my tries (and according to some Google results), the Confiner kind of breaks when the collider is smaller than the current view.
Did I do something wrong there? Because - as you’ve said - I know it’s made for this specific job…

Perhaps you can show pictures of the inspectors involved, and of the undesirable GameView result. That will help me understand what is happening.

Note that the CinemachineConfiner2D does not control the ortho size of the camera - it is up to you to do that. What do you expect to happen when the ortho size is bigger than the confining shape?

I’ve re-integrated CinemachineConfinder2D to better illustrate the issues I have with it.

This is the current state of affairs:
9554800--1350541--upload_2023-12-30_23-15-43.png

As you can see, the boundary (green) wraps around the map (it takes the extreme x and y values and adds an arbitrary amount of expansion). You can also see the boundary being smaller (x-wise) than the viewport.
Now, when I try to pan the camera at all, the virtual camera object moves, but the rendered view does not. This is the case even when zoomed in so the rendered view fits entirely within the boundaries (and that’s the main point I do not understand)!
I’d expect the view to not move outside of the boundaries - but in this scenario in the screenshot, it should move up and down. And when zoomed in, it shouldn’t be restricted at all. Neither of those things happen.

This is the code for CamControl (on the Camera Object) now with the Confiner (the comments from the original post still apply):

if (Input.GetMouseButtonDown(0)) touchStart = camMain.ScreenToWorldPoint(Input.mousePosition);
if (Input.GetMouseButton(0)) {
    Vector3 direction = touchStart - camMain.ScreenToWorldPoint(Input.mousePosition);
    touchStart = camMain.ScreenToWorldPoint(Input.mousePosition);
    if (direction.magnitude < panMagnitudeThreshold) return;
    isPanningOrZooming = true;
    transform.position += direction;
}

And I’m setting the boundaries like this, which is done after map generation:

float boundaryExpand = FreeCamera.GetComponent<CamControl>().panBoundaryOvershoot;
// maxX and such refer to the most extreme coordinates of map objects
CameraBoundary.transform.position = new Vector3((maxX + minX) / 2, (maxY + minY) / 2, 0);
// I'm scaling the Object containing the PolygonCollider2D to encompass the map
CameraBoundary.transform.localScale = new Vector3(Mathf.Abs(maxX - minX) + (2 * boundaryExpand), Mathf.Abs(maxY - minY) + (2 * boundaryExpand), 0);


// another cam is activated and moves to nicely show the entire generated map and ends up being zoomed out all the way

// I'm copying the values from the automatically moving cam, which uses 4 Transforms set to those extreme map coordinates as a target group and thus automatically ends in the position I want my controllable camera to start
FreeCamera.transform.SetPositionAndRotation(AutoCamera.transform.position, AutoCamera.transform.rotation);
FreeCamera.GetComponent<CinemachineVirtualCamera>().m_Lens.OrthographicSize = AutoCamera.GetComponent<CinemachineVirtualCamera>().m_Lens.OrthographicSize;
FreeCamera.GetComponent<CinemachineVirtualCamera>().m_Lens.FieldOfView = AutoCamera.GetComponent<CinemachineVirtualCamera>().m_Lens.FieldOfView;
FreeCamera.SetActive(true);
AutoCamera.SetActive(false);
FreeCamera.GetComponent<CinemachineConfiner2D>().InvalidateCache();

For completeness, those are the settings of the Collider and the Confiner (I’ve tried “Oversize Window”, it didn’t help):
9554800--1350550--upload_2023-12-30_23-27-33.png

I’m highly certain I’m fundamentally misunderstanding something but, for the life of me, I can’t figure it out…

Thanks for that, and sorry for the delayed response. Given that you have code that is attempting to set the camera’s transform - in conflict with Cinemachine - I would also be inclined to believe that you are misunderstanding some fundamentals.

I don’t have enough context to be of much help here, apart from taking random guesses. Would you be willing to send me a project that reproduces the problem?

Hi Gregoryl, first off, I’m incredibly grateful you’re responding at all, no matter the time.

Regarding the issue, I think such a project would be overkill and take even more of your time with little to gain - all the relevant code is on here now anyways.

I should make clear that both camera objects I’m manipulating are, in fact, virtual cameras. I’m not directly touching the actual main camera.
BUT I think you could be on to something there: it’s quite possible that setting the transform of the “FreeCamera” virtual camera object breaks Cinemachine. However, when testing this (I just removed the lines setting the transform of the FreeCamera), it did not make a difference.

Let me lay out my thought process as plainly as I can manage:

  • the camera (the first active virtual camera is “AutoCamera” starts zoomed in quite a bit
  • the map is generated and thus expands
  • the AutoCamera zooms and pans to show the map in its entirety
  • the FreeCamera copies those values with the aim of starting the view of the player zoomed out enough to see the entire map
  • the FreeCamera transfers control to the player

Could you advise on a better approach to achieve this target?

If you’d still like a demo project, could you please tell me how to prepare a Unity project for easy sending (just a zip…?) and whether I should attach it here or somehow send to you directly?

It makes sense that removing the setting of the transform of the virtual camera does nothing, because CM will overwrite the transform in any case. The red flag is: why are you trying to set it in the first place? What did you hope to accomplish?

Your steps sound reasonable, but the devil is in the details. What does “copies those values” in step 4 actually mean in concrete terms?

A simple project with only the camera code and map generation would help, I think. Just zip it up (exclude the Library folder which is large and can be regenerated by Unity) and DM it to me. If it’s too large to attach then you can upload it somewhere and send me a link.