Staying in the lines?

Objective: Limiting the player’s view.

Rose Owen
3 min readAug 31, 2022

Currently, there isn’t a limit to how high/low the player can look, which can be a good thing and a bad thing. Later we will be adding in a model for the player and if they look too far up, they might get a look at the player's actual head, which we don’t want.

Here we can use a nice little useful bit of code that is built into unity, Mathf.clamp. This will let us limit a number between 2 values, eg current speed between 10–50, which would look something like this.

For us, we want to clamp the rotation we give the camera so we can add it into the camera’s local rotation.

This does end up working, but it causes another problem.

Sure, we limited where the player can look but… now we can’t look very high. changing the values in the clamp doesn’t seem to help either, it just ends up causing another bug.

Now when we get to the horizon, it snaps us back to looking straight down. There is a way around this, by changing the value we get from the rotation. Since the clamp is working from 0–360 why not change it so it’s checking from -180 to 180? This does end up using a bit more code but it makes it so much better for the player in the end.

To do this, we still get the initial camera’s rotation and store it, but instead of adding mouse movement to it right away, we check if the number is greater than 180, if it is we take 360 away from it which turns it into a -180 to 180.

Next, we can now clamp that number to what we want it to be, in my case -30 to 30 seems good for now.

Now we can add the mouse movement to a new float value and then input that instead of the clamp we were using before.

In this way, we can limit how high a player can look. If we need to look higher we can just lower the first number, wouldn’t suggest going past -90 though. Also if we want to look lower, increase the second number, also not past 90.

This one was a short little one that ended up taking a little bit of time to look into to get working but the payout from getting this working was well worth the effort. As always, remember to test things out and see you in the next one!

--

--