0

I'm creating a game in LibGDX and am using Tiled as my map system.

I'm trying to contain an OrthographicCamera within the bounds of my TiledMap. I use MathUtils.clamp to achieve this. When the camera is at a normal zoom of 1.0f, it works perfectly. However when the camera is zoomed in further, to lets say .75f, the camera is clamped to the wrong location because it has no information of the zoom value.

position.x = MathUtils.clamp(position.x * (gameScreen.gameCamera.camera.zoom), gameScreen.gameCamera.camera.viewportWidth / 2, gameScreen.mapHandler.mapPixelWidth - (gameScreen.gameCamera.camera.viewportWidth / 2));
position.y = MathUtils.clamp(position.y * (gameScreen.gameCamera.camera.zoom), (gameScreen.gameCamera.camera.viewportHeight / 2), gameScreen.mapHandler.mapPixelHeight - (gameScreen.gameCamera.camera.viewportHeight / 2));

My question: How do I include the zoom value in my clamp code so the camera is correctly clamped? Any ideas?

Thank you! - Jake

SirTrashyton
  • 173
  • 2
  • 3
  • 12

1 Answers1

1

You should multiply by zoom the world size, not the camera position:

    float worldWidth = gameScreen.mapHandler.mapPixelWidth;
    float worldHeight = gameScreen.mapHandler.mapPixelHeight;
    float zoom = gameScreen.gameCamera.camera.zoom;
    float zoomedHalfWorldWidth = zoom * gameScreen.gameCamera.camera.viewportWidth / 2;
    float zoomedHalfWorldHeight = zoom * gameScreen.gameCamera.camera.viewportHeight / 2;

    //min and max values for camera's x coordinate
    float minX = zoomedHalfWorldWidth;
    float maxX = worldWidth - zoomedHalfWorldWidth;

    //min and max values for camera's y coordinate
    float minY = zoomedHalfWorldHeight;
    float maxY = worldHeight - zoomedHalfWorldHeight;

    position.x = MathUtils.clamp(position.x, minX, maxX);
    position.y = MathUtils.clamp(position.y, minY, maxY);

Note, that if a visible area can be smaller than the world size, then you must handle such situations differently:

    if (maxX <= minX) {
        //visible area width is bigger than the worldWidth -> set the camera at the world centerX
        position.x = worldWidth / 2;
    } else {
        position.x = MathUtils.clamp(position.x, minX, maxX);
    }

    if (maxY <= minY) {
        //visible area height is bigger than the worldHeight -> set the  camera at the world centerY
        position.y = worldHeight / 2;
    } else {
        position.y = MathUtils.clamp(position.y, minY, maxY);
    }
Arctic45
  • 1,078
  • 1
  • 7
  • 17