6-Put Boundary on Player’s Movement

At the moment, if we keep pressing one direction (e.g., right arrow), the player will move out of the game view. To make sure the player stays in the sight, boundaries in both x and y directions need to be applied.

In this game, the player will be able to wrap in the x-direction and will be staying below the y=0 boundary in the y-direction.

These criteria can be written out in the as follows:

In the x-direction:
// if x_position > x_max
// x_position = x_min
// else if x_position < x_min
// x_position = x_max

In the y-direction:
// if y_position > 0 (y_max)
// y_position = 0 (y_max)
// else if y_position < y_min
// y_position = y_min
Here, since y is clamped between two values, we can use Mathf.Clamp(value, min, max) instead of the if statement.

After translating the above pseudo-code into the C# script, we have the Player moving within a limited range in the y-direction and wrap in the x-direction, as shown in the gif above.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store