A player of a game is a participant therein. There can be 1 or many players. Multiplayer games are more common these days. Call of Duty, PUBG, GTA are all multiplayer games. But since we are just beginning we will look at the basics first. In this Tech-Recipe we will cover How to Move the Player in Unity.
The player has to have some movement unless it a game like solitaire. Moving on, the player has some speed, some rotation as it moves, etc. Keyboard keys can be used to move the player around the environment.
There are some physical aspects of the player that lead to it moving around. For Example, the player has to have a rigid body attached to it. Also, gravity should be checked.
You have to attach a movement script to the player. There are two ways to write a movement script. Before you write the script there are two terms that you need to know, translation and transform.
Transform: Every object in a Scene has a Transform. It’s used to store and manipulate the position, rotation, and scale of the object. Every Transform can have a parent, which allows you to apply position, rotation, and scale hierarchically.
Translation: Moves the transform in the direction and distance of
You have to apply changes to the transform by using the translation function. You can give integer or float values in the translation function to move the transform of the player. The first way is to simply provide keywords, horizontal and vertical as arguments in the transform. translate function.
How to Move the Player in Unity
Step by step procedure
1. We will use a cube as a player you can add whichever game object you want.
2. Add a rigid body component to the cube.
3. Attach a script called movement write the script like the following one.
The second way is to write individual if statements For Example, if “Up Arrow” key is pressed the Transform should be changed from this to this. For example, if the “Up Arrow” key is pressed then the X-axis value of the vector in the translate function should be positive keeping the Y and Z axis zero.
Multiply the function with speed so you can move at a certain speed. You can also go check in the input Manager which keys are used for horizontal and vertical movements it is better to use the default keys but you can make changes in the import manager.