Camera Boundaries

I’ve tried unsuccessfully to make a script that keeps the player within the view of the camera. My game is an infinite runner type, and I only need the restriction to be for the width of the screen as it’s a portrait orientated game. Any help would be greatly appreciated, thank you!

In LateUpdate you need to check if the left side of your player has passed the left side of the screen, or if the right side of your player has passed the right side of the screen. If it has, then set the player’s position equal to that side’s position.

The left side of your player is (player position - player half width).
The right side of your player is (player position + player half width).

When your player is perfectly on the left side of the screen, his position would be:
(cameraPosition - (screen half width + player half width)).
When your player is perfectly on the right side, his position would be:
(cameraPosition + (screen half width - player half width)).

So here’s the pseudocode:

Is (player position - player half width) less than (cameraPosition- screen half width)?
If yes, set (player position) equal to (cameraPosition - (screen half width + player half width)).
If no, check: Is (player position + player half width) is greater than (cameraPosition+ screen half width)
If yes, set (player position) equal to (cameraPosition+ (screen half width - player half width)).

That is essentially one if/else statement. You would need another if/else if you want top and bottom, and you would use half-heights all around instead of width.

You can get the World Space screen size like this:

float height = Camera.main.orthographicSize * 2.0f;
float width = height * Screen.width / Screen.height;

Then you need to get the half-width of your player. Maybe using “SpriteRenderer.bounds.size * 0.5f” or “Collider.bounds.size * 0.5f”.

I forgot to include the camera position in that pseudocode math. Updated.