How to move Player in 2D Settings

2D Mobile Game

Objective: Allow player to move when player presses A or D key.

To start off, add rigidbody 2d and box collider 2d to the player gameobject. The rigidbody will be reasonable for physics of the player and will be used to change the velocity of the player to make them move in horizontal axis.

The box collider 2d is used to make sure that the player collides with the ground collider and remains on ground instead of falling down.

Then create a player script and add it to the Player gameobject. This script will handle all the behavior of our player starting with our player movement.

Inside the player script, create a reference variable to the rigidbody 2d which we will be using to make changes to the velocity and create another float variable speed which will determine how fast the player will move.

Now inside the Start function, create a reference to the rigidbody 2d using the reference variable. Since the rigidbody is attached to the same gameobject as the script, we can simply take the component without needing to search for the gameobject.

Then inside the Update function, store the value generated by horizontal movement with speed to a float variable and then change the rigidbody velocity to a new velocity changing the value to horizontal input in x-axis.

And this is the final result.

--

--

--

Unity Developer

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

Recommended from Medium

Flutter Android Studio

Android 11 First Developer Preview Released: Download For Pixel Devices

Customizing a Drawer Element in a Quick App

Displaying images in Android app: maintainable, testable, painless. Part I

CI/CD pipeline for Android via Github workflow

Gray Screen Issues in Flutter

TextView & <img>

Android CameraX

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
Niraj Karki

Niraj Karki

Unity Developer

More from Medium

Creating Character Animations in Timeline and Tackling Some Known Issues

Creating a Sci-fi Lab Room

From Prototype to Art

2D Mobile Game: Tilemaps