Simple Player Movement in Unity 2D

Chris Hilton
2 min readMay 24, 2021

--

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:

Visual Studio 2017 — Player script

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.

Adding simple movement to our player through code

Essentially we have:

  1. Created a new public float variable to control our player’s speed
  2. Accessed Unity’s built in Input Manager to assign the horizontalInput and verticalInput variables to their respective axis’s.
  3. 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).
  4. 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.
  5. 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:

Simple movement to our Player cube asset

--

--

Chris Hilton
Chris Hilton

Written by Chris Hilton

Passionate Unity Game Developer

No responses yet