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:

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

--

--

--

Passionate Unity Game Developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

The Complete Python Developer in 2022 — Zero to Mastery

How to create a fully automated job board using no-code tools (Automatio + Webflow + Google Sheets…

Using a Bash Script to Connect VSCode To a Salesforce Org

How to make sure TIBCO BusinessWorks 6.X

How to make a HTML and CSS animation

HOW I HACKED NASA WITHOUT HTML !!

Difference between MySQL and Firebase? Difference between SQL and NoSQL

The Return of the JWT — How I Saved Christmas Part VI (SANS Holiday Hack Challenge 2017 Write-up…

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Chris Hilton

Chris Hilton

Passionate Unity Game Developer

More from Medium

Transposer Virtual Camera Explained in Unity’s Cinemachine

Lighting your scene in Unity using the URP

Adding Post-Processing Profiles in Unity

Adding a camera shake effect