Unity/C# Challenge 2: Creating Player Bounds in C#

Challenge: Prevent the player from moving off the screen.

With player movement implemented, the player object can be observed to fall off the edge of the screen:

To prevent this, you must first establish the outer bounds. For our purposes;

Upper bound is 0,

Lower bound is -3.8,

Right bound is 12.5,

and Left bound is -12.5.

The initial fix involves creating a vector of (0, 0, 0) upon reaching the (Upper) bound:

Which stops the movement along the y axis but leads to “snapping” back to 0 along the x axis:

To fix, equate the unused axis (x if you are coding the y axis movement, and vice versa) with it’s current location:

with the full code for all bounds appearing like:

And resulting in:

BONUS: the transform.position code can be used in order to make the object appear to “wrap” around the screen by flipping the x coordinate (for example):

Resulting in: