How to Automatically Adjust Camera2d limits

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Twinxs

enter image description here

First I tried using this code below. The problem is I want the limit to re-adjust based on the currently filled pixel/tile by my ground tilemap. So basically imagine the empty pixel on the scene as collision for my camera limit. I don’t know it makes sense.

func _ready():
var tilemap_rect = get_parent().get_parent().get_node("YSort").get_node("Ground").get_used_rect()
var tilemap_cell_size = get_parent().get_parent().get_node("YSort").get_node("Ground").cell_size
$Camera2D.limit_left = tilemap_rect.position.x * tilemap_cell_size.x
$Camera2D.limit_right = tilemap_rect.end.x * tilemap_cell_size.x
$Camera2D.limit_top = tilemap_rect.position.y * tilemap_cell_size.y
$Camera2D.limit_bottom = tilemap_rect.end.y * tilemap_cell_size.y

here is a representation of what I wanted to happen. the yellow box is camera limit for the initial state of player, once the player reaches the blue circle the camera limit re-adjusts as the green box. finally once the player reaches the pink circle the camera limit re-adjust to the red box. I hope it makes sense

:bust_in_silhouette: Reply From: aidave

There are many ways to do it, but I don’t think there is a built-in solution for this.

You could try an algorithm of “growing” the four sides of a Rect2, starting as a small square from your player position, where each side stops growing when it hits a bad spot (or hits max size), then adjust camera limits based on the final rectangle.

:bust_in_silhouette: Reply From: CassanovaWong

Well, using that code in the ready function means it won’t readjust because it only happens once.

I would include the code you have, or something like it, in the player move script. So that, when the player’s distance to the destination is at a suitable arrival point, the camera limit will adjust.

Or have an area2d at those arrival points so that when the player enters the area2d, the limits adjust.

Several other ideas come to mind…

How are you moving the player?