Player Clamp

Ryan McCoach
2 min readMar 27, 2021

--

Player Clamping is not allowing the player to move outside of game view. This only requires one line of code with the use of a helpful math function called Mathf.Clamp. What this math function requires is the value you want to restrict and the range you want to to restrict that value between.

The value we want to constrain is the Player’s X & Y position. Now, we need to selected the range that we want to constrain those positions between (the values at the edges of the game view), so you will need a Min and Max value for both the X & Y. To figure this out, just requires you to move the Player around and take note of X and Y coordinates using the Inspector in Unity. For the X, we clamped the it between -9 (left side of the screen) and 9 (right side of the screen). For the Y, we clamped it between -3.8 (bottom of the screen) and 5.8 (top of the screen). The Mathf.Clamp makes the code much more efficient with the alternative being a bunch comparisons using IF THEN statements.

--

--

No responses yet