Simple Player Movement in Unity (2D Shooter Project)
Have just finished setting up the player’s movement in this 2D Shooter Project. While I’m fairly familiar with C# scripting and programming player movement by this stage, there were still a few solutions and best practices that were quite new to me (and I’d like to make a note of them here).
The first was in using the transform.Translate method, as previously I’d been more used to simply setting the transform.position to a new Vector3 with an increased X or Y value or applying force to the GameObject to create movement.
The second was in finally using Input.GetAxis as opposed to Input.GetKeyDown, which I’ve no doubt is better practice and allows for greater cross-platform support. As a result of these two, the basic 2D movement code for the player looks like this:
private void PlayerMovement()
{
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");Vector3 direction = new Vector3(horizontalInput, verticalInput, 0);
}
Combining the vertical input and horizontal input values into a Vector3 definitely feels like a cleaner practice than multiple transform.Translate statements and more Vector3 declarations than are necessary.
Aside from this, I also learnt about a more efficient way of clamping player movement. As opposed to if and else if statements checking, in this case, the transform.position.y value, we can use Mathf.Clamp to perform this clamping in a single line:
transform.position = new Vector3(transform.position.x, Mathf.Clamp(transform.position.y, _yMinVal, _yMaxVal), transform.position.z);
It’s these kinds of best practices that I’m particularly interested in learning in the 2D game development module I’m currently taking.