Player Boundaries in Unity

With the ability to move the player in the X and Y directions in the scene, we now have objects that can move beyond the view of the camera, if the player were to instruct them to do so. We now need to impose some limits to that movement to keep things, like the player, in view. We are going to do this with ‘if-else’ statements.
‘if-else’ is the code way of saying ‘if condition (A) is met, then do thing (X), otherwise do thing (Y)’. Another version is ‘if condition (A) is met, then do thing (X), if condition (B) is met, then do thing (Y), ‘’else’’ meaning roughly ‘otherwise’, then do thing (Z).
In our case, we want to restrict the movement of the player object in order to keep it within the camera’s view. We will first get the objects furthest position values to the left and right, the x-value, and the upper and lower limits, the the y-value. We do this by manually positioning the object in the Unity editor at the furthest desired positions, in the Game View, and take note of them from the Inspector.

Next you will want to define these limits in your if and if-else statements. Also, you will do this in the Update so that it gets updated positions with every frame of the game. First we will take care of the Y axis for up and down movement. Using the sliders we get an upper limit of 0 and a lower limit of -3.8. We put these values into the if portion and use a new Vector3 in the else portion as in the code shown here.

Then we move on to the horizontal limits. In this case we are defining these limits so as to keep the player on the screen. That looks like this…

You could also set it up so that the player object could move horizontally with a wrap-around, where you would be swapping the y positions of the object as it passes just out of the bounds of the camera. That would look something like this.

Altogether, your script will look like this…

And the result in game view is this…

And, now you control the boundaries of movement for your player object.