Simple Player Movement in Unity 2D
Adding a player movement script using Unity’s legacy input system.
Setting Up the Scene
Create a new 2D Unity project and setup a new scene. Go to File>New Scene and click on the 2D button in the Scene view. Add a simple cube to your scene and we’ll name this cube, “Player.”
Adding a PlayerMovement Script
We need to write some code to make the Player move according to our input. Create a new C# script, name it “PlayerMovement” and attach it to the Player.
Writing the PlayerMovement Script
Open the PlayerMovement Script and edit the default code as follows.
You should now save your script and go back into your Unity Project. When your press the play button, you should now be able to move the player using the arrow keys or the WSAD keys.
How does this work?
We created a floating variable for both horizontalInput and verticalInput linking them respectively to the Input.GetAxis() preset Unity inputs. This is W and S or UpArrow and DownArrow for the vertical axis, and A and D or LeftArrow and RightArrow for the horizontal axis.
We are then creating a new Vector3() based on which input is being used.
Finally, we are taking that input times the speed variable (_speed), times real time (Time.deltaTime) and assigning that value to the new Vector3(), moving your Player to that location.
Summary
This concludes our Simple Player Movement in Unity 2D. You should have a working PlayerMovement script that allows you to move your Player around using keyboard inputs. My next article will briefly cover Variables: The Building Blocks of Programming.