Using MathF.Clamp to Give Our Player Boundaries in Unity

Chris Hilton
2 min readJun 7, 2021

--

Objective: To tidy up our player boundaries code by using the MathF.Clamp function!

So far we have the following code that is stopping our player from moving outside of the boundaries defined below:

Player boundaries
Game player player boundaries

As you can see the code itself looks like a big wall of text and is not very easy on the eyes to understand, so we are going to clean this up by refactoring the code using the Mathf.Clamp structure whilst keeping all the same constraints we have for the players boundaries. See below:

Mathf.Clamp for the player’s boundaries

Let’s break this down:

We are saying that our players transform.position is equal to a new Vector3(X,Y,Z) of which we are going to clamp the X and Y axis’s respectively to their defined _minX, _maxX and _minY, _maxY. We are simply going to say for the Z-axis that this is 0 as it is irrelevant for our game.

Mathf.Clamp
This structure takes the following syntax:
public float Clamp(float value, float min, float max)

In our case for our X-axis we are going to say:
Mathf.Clamp(transform.position.x, minX, maxX)
// The float value that we are wanting to restrict between the min and max is the transform.position.x value.

In our case for our Y-axis we are going to say:
Mathf.Clamp(transform.position.y, minY, maxY)

And for our Z-axis we are going to leave this as 0. If we were also wanting to clamp this we would follow the above.

Let’s take this a step further:

If you are wanting to shorten your code even further, we can simply have 1 value for the X and use the inverse or negative value as shown below:

This won’t work for the Y values as they are different.

Useful Links:
https://docs.unity3d.com/ScriptReference/Mathf.Clamp.html

--

--

Chris Hilton
Chris Hilton

Written by Chris Hilton

Passionate Unity Game Developer

No responses yet