2D Galaxy Shooter — Player Bounds Using “if” and “Mathf.Clamp” Statements
Hello all!
Today, I’m going to go over how to set up bounds for the player so they can’t leave the vertical play area and a wrap system so if the player goes off the edge of the screen, they appear on the other side.
For my vertical bounds, I used “Mathf.Clamp”.
This new Vector3 is saying that when the player reaches 0y or -3.8y at any point on the x axis, that they can’t move anymore. The Mathf.Clamp only allows the player to move between those two points.
For the horizontal wrapping, I used an “if” and “if else” statement.
This is saying that if the player reaches greater than or equal to 11.3x, then the player will be sent to -11.3x, thus making a wrapping screen. The “if else” says the same thing but in reverse.
Now that our movement is complete, we will want to clean up our code.
To do that, we need to create a new method called,
“void CalculateMovement()” and move all our movement code from the Update method to there. This will let us find where your movement code quick with out having to dig through tons of code for debugging purposes.
To finish it up, you will need to reference CalculateMovement() in update so the script can find your code.
This was player bounds and cleaning up code!
Thank you for your time!