2D Mobile Game: Player Movement

Intro

In this article I will cover how to add player movement and controls using the Rigidbody2D and the Input system.

RigidBody2D

The first thing in creating the player movement and control is adding a Rigidbody2D to the player. The Rigidbody2D will place the player game object under the control of the physics engine on the X & Y since it is 2D.

Now that we are using the physics engine, gravity is now added to the player and this results in the player falling through the ground. The reasons for this is the player doesn’t have a collider that will detect the ground or tilemap colliders.

We add a Box Collider 2D to the player and edit it to fit the player sprite.

This now has the player colliding with the ground, so we no longer fall through it due to gravity.

The Script

We are going need a reference to the Rigidbody2D to make use of the physics engine, so we will create a private Rigidbody2D _rb. In the OnStart, we can just get the Rigidbody2D component and do not have to find it since it is already on the player.. We perform a null check to make sure we have the Rigidbody2D.

In OnUpdate, we are going to get the Horizontal Input value and store it in a local float variable “horizontalInput”. The Input.GetAxis(“Horizontal”) returns an incremental value between -1 and 1. When the left arrow or A key is used the returned value will be an incremental value up to -1. When the right arrow or D key is used the returned value will be an incremental value up to 1. When neither of the keys are being used, 0 will be returned.

With the horizontalInput value, we can set the Rigidbody velocity to a new velocity of Vector2. The Vector2 needs a X and Y value. The X value will be the horizontalInput that is being returned (-1,0,1) and the Y value will be the current velocity on the Y.

The player can move left and right, but you will notice that when the left and right movement keys are finished being pressed, the player still slides to a stop. This is due to the horizontal input incrementally return from either 1 or -1 back to 0. If you want a more responsive start and stop will need to get the Raw Axis.

This will return either -1 (left movement key), 0 (no key), or 1 (right movement key) and none of the incremental values.

Movement using the Raw Axis Values

The last thing is freezing the rotation of Rigidbody on the Z axis. This will stop the player from rotation around that axis and prevent it from tipping over.

--

--

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