A quick tip on player movement constraints in a 2D game

Luke Duckett
3 min readMar 28, 2021

Mario never left the screen, and neither should our player. There are a few ways we can lock the player to our screen. In this article, I will focus on bounding the player to the screen with a function to wrap the player from one side to the other.

In most games, we attach a camera to the player and write up some code, so it has the functionality we want then we are done. This works well in the 2.5/3D world. What about a simple 2D game like in our example of a space-themed shooter?

Simply we decide how far we want to allow the player to go on the axes. In this example I want the player to be able to move to the top of the screen without moving out of camera range. At the moment though our player can move as far as they want.

Let us make a variable for our constraints on our y-axis, one for the highest and lowest point.

Now we can move our game object and record these values so we can use them later.

I’m going to separate the logic here into another function. We basically tell our program if we reach or exceed our bounds keep our x position and override our y position with the bounds we have set.

Now let’s see it in action.

As you can see the player can no longer leave the screen from the top or the bottom.

Now we have two choices moving forward. We can bound the player on the x-axis so they can only move so far as we did with our y-axis, or we can have the player wrap to the other side. In this example, we are going to wrap the player to the other side of the screen when they move to the edge.

The first thing we want to do is add our logic to our Constrain Movement function. We basically want to keep our current y value but replace our x value with a value that moves the player to the other side of the screen.

Now to get the bounds of where we want to wrap our player. We can do this as we did before by moving our game object to where we want to begin the wrap. Then just copy this value and paste it as a negative value and you will have your bounds for the left and right.

And there we have it, our player now has bounds on their position with a nice system for wrapping from one side to the other.

That's all for now.

--

--

Luke Duckett

🎮 First Nations Unity Dev from Wonnarua country 🏞️ | From Player to Lifelong Learner: Crafting Games, Debugging Code, and Embracing New Technology