Restricting Movement and Pseudo Code

In my last post, I created a simple character controller, but what’s to stop me from making my character disappear off screen? We need to add limits.

Say we set our limits to be 10 units in the horizontal and vertical axes from 0, 0, 0. We need to keep our player transform within -10 and 10 on the X axis, and -10 and 10 on the Y axis.

To do so, we can use if statements. These statements check if something is true, and if true, proceeds with the encapsulated code. If not, it’s skipped over.

The above code would essentially lock our movement on the X axis from going past 10 units, while also keeping our current position on the Y axis. But I wanted to go one step further and make my player wrap to the other side of the screen. To do so, I simply set my new Vector3 to be at -10 on the X axis, thus setting my position to the other side of the screen.

The same wrapping wouldn’t quite work in my current project for the vertical axis, so we could just settle for the if statement. But I feel as though it’s a bit janky under the hood, what our player would be doing is constantly teleporting back to the limit we had set, even if not visible.

Luckily, Unity has a math function called clamping. We can set a clamp for the Y Axis using the following code:

Mathf.Clamp allows us to select a component we want to limit, followed by the two bounds we want to set. To now put this variable in place, we need to set it within our position.

Now our player controller has limits, creating a much better starting functionality. But how do we know what’s actually going on in our code? It would be simple enough to just have our bounds set with if statements, but now we have a teleporting feature and some scary line including the word Math…

That’s where psuedo code comes in to play. Psuedo code allows us to add comments with ‘//’. We can simply state what each section is, or we can fully type out what we want each line of code to do in plain English.

The latter is great for experimenting with creating new features, as it gives a simple reference point to try and achieve. But personally I would delete it afterwards, I don’t want my scripts to be double the length of what they need to be.

That’s where the simpler comments come in handy. I like to use the ‘tab’ key a few times to set what I consider to be headers off to the right hand side of my code block. Now when I look back in my scripts, or I’m working with other developers, they can easily see what I have intended to enable with each block of code.

Here’s a snippet of my player controller code. Ignore the bland boring look of it, I’m away from my studio whilst writing this article and have had to use GitHub to access my script for reference. Remember that article about how good version control is? It’s coming in handy already!