Space Shooter: Player Bounds

In the last article I covered the movement of the player. In this article I’ll demonstrate how to set up some bounds for the player and how to achieve a “wrapping” effect when the player goes to far to the left or right.

Right now if I play the game and hold the left or right buttons I’ll eventually leave the screen. I want the game object to “wrap around” to the other side. What I’ll actually be doing is teleporting it from one side to the other but it will appear to wrap.

I cleaned up my code from the last article as well. I just created a Movement function and put all the movement code in it. I’m calling it in Update.

Here, all I’m doing is saying that if the player’s X position is less than or equal to -16f, the transform.position will be equal to whatever transform.position.y and z are, but x will specifically be 15.9f. This makes it appear on the other side of the screen. Same thing with it being 16 or more. It will appear at -15.9f. Simple as that!

SO now for the Y position. I dont really want to wrap it. So I can do something similar. If the player’s Y position is greater than or equal to 0 and less than or equal to -6.5f just set its transform.position.y = either 0 or -6.5f. But look at this monolith of code…

There is a way better way to handle this. Mathf.Clamp. Unity — Scripting API: Mathf.Clamp (unity3d.com)

This takes in a value.. our y position.. and a minimum and a maximum value. So the code would look like this instead. WAY Better.

The goal here is to make the code more readable. The result is this!

I’ll be setting up a laser and it’s functionality in the next few articles. Be sure to stick around for that! Until next time.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Gerald Clark

Gerald Clark

Father Game Developer Music Composer Sound Designer