How to keep player inside a defined area?

Godot 4.3.stable

I have a vertical game area of 720x1080 and 2 parallax layers for the background layer and a layer of bushes. I used clamp to keep my player inside the game area so that they’re not able to leave the area when moving. There’s also camera2D on the player scene as a child of CharacterBody2D.

My issue now is that when the player moves on the x-axis the background will continue to move, revealing the space beyond the boundaries of the game area. But the player will be blocked from going any further than the clamped area. The player also can only move within the area defined by the clamp function I think? When they’ve walked a certain distance up/down they’ll get blocked from moving further.


The idea is that the player can walk infinitely along the grass area on the y-axis, with the background/bushes moving, but still stay within the confines of the bushes when moving on the x-axis. If I remove camera2D from the player scene, the viewport does stay within the game area, chracter cannot move out of the sides, but they will disappear from the top and bottom of the screen. There is also no parallax scrolling when moving.

I’ve no idea how to move on from here, this is my first attempt to make something outside of tutorials.

Any help is appreciated!

You should add invisible walls that the player can collide with.

I wouldn’t add level boundaries to the player script, as this will induce coupling between the level and player. And if you update the level you will most likely have to update the player too. (Unless you make a specialized system, but you don’t need too if you create physical boundaries and utilize the physics engine properly)

If you want to allow the player to reach the edge of the screen but not have the camera show the edge of the level. Then you need to put constraints on the camera too.

Hi,

So I’m still pretty new, but I believe the only problem is clamp actually takes in 3 parameters, (value, min, max).

You could try adding an area2d to the bushes and then use the on_area exited signal to reset the players position to their last position. Or probably on_body_exited.

Thank you. I’ve added collisionshape2D as invisible walls on the main scene and it stopped the player from moving out of the screen.