Code Clean Up With Mathf.Clamp

Pete Thomasberger
2 min readApr 19, 2021

In the last article about Pseudocode, we create an If statement and an If Else statement that restricted the movement boundaries of our Player GameObject on the Y-axis.

Basically, we said that when the Player GameObject reaches 1.5 on the Y-Axis, it cannot go any higher on the screen, and if it reaches -3.8 on the bottom of the screen, it cannot go any lower. This did accurately reflect our Pseudocode, but there is a more optimized way to achieve the same result with fewer lines of code. By creating a space on the screen with a maximum and minimum height that the Player GameObject could navigate within, we were effectively creating a clamp on the Y-axis, and there is a function just for this operation called Mathf.Clamp.

Mathf.Clamp can be used to create a clamp between a minimum and maximum set of float values, and in our case, our minimum and maximum height on the Y-axis. To use Mathf.Clamp, we must identify what is that we are clamping, for us it is the Y-axis, so we would use transform.position.y, and what the minimum and maximum values are, which is -3.8f and 1.5f. Here is what that looks like:

Now, by itself, we cannot use this line as this only works out the position for the Y-axis. So, just as we did within the If statement, we will need to create a new Vector3 and use our Mathf.Clamp function as the Y-axis value. Here is what the full code will look like:

To break this down, we are generating a new position for the Transform of the Player GameObject within a new Vector3 that has a clamped boundary between 1.5 and -3.8 on the Y-axis on our screen.

We have effectively optimized our code by consolidating 4 lines into just one line of code with the same end-result.

--

--