Now that we have a player object that can be controlled by keyboard input, we need to set some boundaries in 3D space so that it cannot move off of the screen. We’ll do this with some if-statements in the Update method to check the current position each frame.
We’ll start with creating the boundaries for the y-axis. For our game, a y-value of 0 is a good upper bound for our movement, and we’ll use -4 as a lower bound. Two if-statements will need to be made: one to compare the current y-position against the upper bound, and one for the lower bound. If the cube goes out of bounds, set the transform.position to a new Vector3, keeping the current x and z positions but setting the y-value to be equal to the boundary.
This code could be a bit cleaner though. Instead of directly putting 0 and -4 in the if-statement and the vector definition, it is a better practice to save those values in their own variables and replace the numbers in the code. That way they won’t need to be changed in multiple places in the code. I created some variables for the x-values as well.
The horizontal boundaries use the same logic, but I want the cube to wrap around to the other side of the screen when it reaches one boundary. I just need to set the x-position to the opposite boundary and it should wrap around the screen.
Check it out! It wraps around nicely and is constrained on the y-axis.