Simple Player Movement in Unity 2D
Objective: Giving our player some simple movement in our 2D Unity game
You have managed to download Unity, open your first project, change your editor layout to look more professional, learnt how to add an asset to a scene and add a script to that asset and are excited for your first piece of code to get your player moving. Let’s jump into it!
Adding code to make our player move
Double click or hit enter when you have selected the script to open it within Unity and you should be presented with the following screen:
Without getting into the knitty gritty of understanding Input systems within Unity as this can be quite extensive, essentially we are going to give the ‘Player’ game object asset some simple movement when the user presses W, A, S & D keys on the keyboard.
Essentially we have:
- Created a new public float variable to control our player’s speed
- Accessed Unity’s built in Input Manager to assign the horizontalInput and verticalInput variables to their respective axis’s.
- Assigned these variables to a new Vector3 structure — HorizontalInput for the x-axis, verticalInput for the y-axis and 0 for the z-axis (as we don’t want the player to move along the z-axis).
- Used the transform.Translate method, incorporating our player’s Vector3 direction, multiplying this by playerSpeed and multiplying this by Time.deltaTime to move the cube in real time.
- Ultimately achieving our objective of adding simple movement to our player’s cube!
Don’t forget to save your changes and head back over to Unity and hit Play to see the changes to your game. You should be able to freely move the ‘Player’ cube around the screen up and down, left and right as shown below: