Setting up player Bounds!

And we are back! Last time we have granted the player the possibility to move around - and today, we will introduce a few limitations. Since our camera does not yet move - but is static instead, we have to make specific rules so that our player does not disappear and gets lost somewhere off the screen.

We are going to be working on two restrictions:

  • If the player moves over the screen edge on the X-axis( going left & right ), he will appear on the other side of the screen.
  • Disallow the player to move on the Y-axis( up & down ) if he is at the edge of the screen.

To do this, we will have to figure out at which values do these actions occur. We have to move your player down/right/up & left to/over the edge of the game screen and figure out the values. For me, these values are as follows:

Nifow that we have these values, we have to update our ‘Player’ script with ‘Conditionals’ - and for that, we will use simple if statements.

First up, we take a look at the X-axis. We have to check whether the player is at or beyond the -11f/11f position on the x-axis and change his positioning to the opposite number. And this is how it is done!

Now, whenever you try to go off the screen, you will reappear on the opposite side!

Next, we take a look at the Y-axis. We have to check whether the player is at the 6f or -4f position on the y-axis. Then, change the positioning on the y-axis to that value whenever he tries to go beyond.

Alternatively, we can use the ‘Mathf.Clamp function. Clamp Returns the min value if the given float value is less than the min. Returns the max value if the given value is greater than the max value. Use Clamp to restrict a value to a range defined by the min and max values.

We have to set our position to a new Vector3 and Clamp the possible values of the Y position between -4f and 6f like so.

If you run this code, you will see that you will not be able to go past those values and hit an invisible barrier.

But that is it for now, thank you for reading and feel free to follow me for more articles — and as always, good luck and see you next time!

Aspiring and eager beginner Unity developer