• 2D
  • How to restrict player camera to game area?

Hi everyone.

I'm making a 2d action RPG with some large levels, larger than screen size, so I'd like to restrict the player camera so that it stops moving with the player when it hits the boundaries of the map. I heard you can do this if using tiles but I'm using a background sprite for my map.

I'd appreciate any help with how to do this. Thanks :)

You can set the limit_bottom (documentation), limit_right, etc properties to constraint the camera so it stays within certain bounds. I'm not sure how you do it with tiles though.

Alternatively, if you know the limits of the map, a simple AABB check might also work, though it is probably not as performant:

if ($Camera2D.global_position.x < MIN_X):
	$Camera2D.global_position.x = MIN_X
elif ($Camera2D.global_position.x > MAX_X):
	$Camera2D.global_position.x = MAX_X

if ($Camera2D.global_position.y < MIN_Y):
	$Camera2D.global_position.y = MIN_Y
elif ($Camera2D.global_position.y > MAX_Y)
	$Camera2D.global_position.y = MAX_Y

Sorry, but where do I need to put that code and what function does it need to be under? I've tried it in the player script and camera2d (child of player) but nothing seems to happen (no errors though).

Which code? The Camera2D AABB code?

You'll need to add it in _process or _physics_process. The Camera2D node will need to be named Camera2D exactly, or you will need to change $Camera2D to reflect the node name. Additionally, the Camera2D node will need to be a child of the node the script is attached to.

If you want to attach the script to the Camera2D directly, you can use something like the following:

if (global_position.x < MIN_X):
	global_position.x = MIN_X
elif (global_position.x > MAX_X):
	global_position.x = MAX_X

if (global_position.y < MIN_Y):
	global_position.y = MIN_Y
elif (global_position.y > MAX_Y)
	global_position.y = MAX_Y

You can actually simplify that code considerably with clamp:

global_position.x = clamp(global_position.x, MIN_X, MAX_X)
global_position.y = clamp(global_position.y, MIN_Y, MAX_Y)

Hm, works well but of course only if the player starts in the middle of the map. Do you know how I might be able to keep the camera away from the edges when the player spawns near the edge? Like, it's at an offset and then it centers on the player once he moves towards the middle. Otherwise, I'm thinking I might just have to extend the level past the invisible walls so there's stuff in the distance rather than just grey.