Creating Player Boundaries

Kenny Pruitt
Unity Coder Corner
Published in
3 min readFeb 21, 2023

Objective: Creating Player Bounds

By allowing the player to move, you must set boundaries where the player cannot go. This is used in every game as a way to set some of the rules of the game. A few examples of this are, being unable to move out of view, being unable to pass through objects, or being able to touch the ground so you don’t fall through it.

In this example, this basic player object is able to move out of view of the screen.

An easy way to limit this in a 2D game such as this, is to just check the Player position after movement is attempted and if the movement exceeds that of which is visible on the screen, then force the position to that of something that is still on the screen. To do so, we can simply use if else statements to check and set position if needed.

To clean up our code a little, we can also create a function to check specifically for the Player bounds just to clean up our Update function a little. To do this, we can simply create a new void function and then call it in the Update function.

Now if we go into Unity and press Play, you will see that our player object is limited to what we set the bounds to.

If you would prefer to make the player wrap around to the other side when they get to their horizontal limit, you can simply adjust the code so that when the player is off the screen going in one direction, their transform.postion will be moved to the opposite side.

Now that we have our code updated, we can go back into Unity and see that our Player is able to wrap around the screen, or change position to the other side of the screen when moving too far to either direction.

Just to clean up our Update function a little and remove some of the if, else if statements, what we could do is move our PlayerMovement into its own function, and use a clamp on the vertical movement. A clamp is a function that can take a variable and limit its minimum and maximum values, simply my assigning them in the Clamp. To do so we would simply use the function Mathf.Clamp(ourVariable, theMinimumValue, theMaximumValue). In C# you want to try and avoid long lines of if, else if statements when possible, just to help the game run more performant.

--

--

Kenny Pruitt
Unity Coder Corner

Unity Game Developer, C# Developer, and Software Engineer