This tutorial will show you how to set up four directional player movement using the Unity Playground scripts.
- Unity Core Concepts (Official Unity Tutorial)
- Unity Project and Version Control Setup
- Unity Feature: Sprites
- Unity Feature: Physics System
- Playground Script: Move
Step 1 – Create Player GameObject
Create the player’s GameObject by dragging the player’s sprite into the Scene Window. This will create a new GameObject with a SpriteRenderer component attached to it.
Rename the new GameObject “Player” so you don’t get confused later.
Step 2 – Add Move Script
Select your new Player GameObject. Add the Move script to the Player, either by dragging the script in from the Project Window and dropping it on the Player in the Hierarchy Window, or by clicking “Add Component” in the Inspector while the Player is selected and browsing to or searching for the “Move” script.
When the Move script is added, a second component, Rigidbody2D, will also be added. This is a Physics component that the Move script will use to move the Player using Unity’s physics system.
Before moving to the next step, select the Player in the Hierarchy and check the Inspector. Make sure both the Move component and the Rigidbody2D components are attached.
Step 3 – Adjust Settings
Press Play and test the game. You should be able to move the player, but there are some issues with the settings. Make some adjustments as suggested below:
- Gravity is on. Turn this off in the Rigidbody2D component by setting the gravity scale to 0.
- Once you move, your player never stops. This is because of Newton’s first law of motion: An object in motion tends to stay in motion. It’s like this in the real world too, but here, we have lots of things slowing us down – friction, air resistance, etc. Set the Rigidbody2D component’s friction to something other than 0 – try 5 and adjust as needed.
- The player may move too fast or too slow. Try changing the speed on the Move component, and the friction on the Rigidbody2D component, until you get a good balance.
- The player doesn’t move using the correct controls. You can change between WASD or arrow controls as desired.