Setting Game Bounds in Unity 2D

Niraj Karki
3 min readApr 28, 2021

--

Day 6- Making 2D Space Shooter Game

When working on a game where your camera remains static but player can move around, it is important to set bounds since if the player moves outside the range of the camera, you won’t be able to see the player on your game screen.

As you can see when your player moves around, it can go out of range of the camera and it won’t be visible on your screen. So how do we solve this?

You can add this script on your update method to set your bounds. Here, if your player position in x axis is 9 (it may be different on your PC so move your player on scene view and take the position where your player starts disappearing on game view) then your player cannot go beyond. How does it happen? inside the if statement, you are setting your player position to be reset to 9 whenever it tries to go past the given number. You can still move up and down since you are not specifying a constant value 9 as your position on Y axis instead taking the position where you are at right now which updates per frame.

the if statement works to bound on the right side so you can set bounds on the left by using else if or if-statement placing the negative value of the number used on right or you can move your player on the scene view to know which position to set as your bounds.

You can do the same in Y-axis to set your bounds when moving up and down as well.

You used an easy way of setting bounds to your player but there is a more slimmed out way of doing it.

Here, we are indicating that you can move around x-axis while the Mathf.Clamp constraints the value between min and max. In the above image, you can see that you are specifying a direction to create bounds on i.e. Y-axis and the bound is set between min value of -3.9 and max value of 0.

This is what you get after you set bounds on all sides.

But if you want your player to appear from the left when going out of bounds on right then you can use the above code. Here you are basically saying that if you have position value greater than this then set position to the negative value of the bound position.

You can now decide which type of bounds you are going to set depending on your game.

--

--