Restrict Player movement with Bounds
How to create limits for movement in Unity
Previously we made our player object move based on user input. This time we going to restrict how far the player can move.
How to figure out the boundaries
Let’s determine the minimum and maximum positions in the X and Y axis (+Z axis if you are moving in 3D). Make sure you have set an aspect ratio for the game view or the boundaries will be weird when you resize the game screen.
The easiest way is just move the object around. Look at the inspector and note the outer positions.
Update Player script to create restrictions
We will be using If statements. For more information check out this article:
Open the player script. Using if-then logic, we start off with pseudocode to create the necessary logic.
If player position y is greater or equal to max y position
then set player position to max y position
We will need to repeat this 4 times for each outer boundary. Using the inspector we already noted the minimum and maximum positions. Before the Start()-part we will assign these values. The code is:
[SerializeField] private float _speed = 5f;
[SerializeField] private float _maxPosX = 11.4f;
[SerializeField] private float _minPosX = -11.4f;
[SerializeField] private float _maxPosY = 4f;
[SerializeField] private float _minPosY = -4.2f;
// Start is called before the first frame update
//set starting position
transform.position = new Vector3(0, -3, 0);
// Update is called once per frame
//move player based on user input
transform.Translate(Input.GetAxis(“Horizontal”) * _speed * Time.deltaTime, Input.GetAxis(“Vertical”) * _speed * Time.deltaTime, 0);
//player position restriction on Y axis
if (transform.position.y >= _maxPosY)
transform.position = new Vector3(transform.position.x, _maxPosY, 0);
else if (transform.position.y <= _minPosY)
transform.position = new Vector3(transform.position.x, _minPosY, 0);
//player position wrap around on X axis
if (transform.position.x >= _maxPosX)
transform.position = new Vector3(_maxPosX, transform.position.y, 0);
else if (transform.position.x <= _minPosX)
transform.position = new Vector3(_minPosX, transform.position.y, 0);
Wrap around horizontally
In our example we deliberately set the outer bounds of X so the player would be off screen. This is so we can create a nice looking wrap around effect.
If x position is greater then max x position
then set x position to min x position
The same will be done for the min x position detection. The result should look like this: