Player movement
- Game Development course
- Advanced
- Lesson 50/71
- 4 min
Write the player movement script step by step.
Player Movement and Input Reading
The first step in moving the player is gathering directional input from the keyboard or controller. The functions Input.GetAxis("Horizontal") and Input.GetAxis("Vertical") return smoothed values between -1.0 and +1.0.
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = new Vector3(x, 0, z);These readings are assembled into a 3D movement vector (Vector3).
Applying Movement and Time.deltaTime
To guarantee frame-rate independent locomotion, the velocity vector must be scaled by Time.deltaTime. Movement is then applied via transform.Translate.
void Update() {
float x = Input.GetAxis("Horizontal");
Vector3 move = new Vector3(x, 0, 0);
transform.Translate(move * speed * Time.deltaTime);
}This multiplication ensures the character traverses the exact prescribed distance per second regardless of whether the game runs at 30 or 144 FPS.
Practice Player speed control
Define a Start method. Inside, declare float speed = 5.0f; and print "Oyuncu hizi: " + speed to the console.
Starter code
using UnityEngine;
public class PlayerMovementTester : MonoBehaviour
{
// Start icinde speed tanimla ve yazdir
}Sample solution
using UnityEngine;
public class PlayerMovementTester : MonoBehaviour
{
void Start()
{
float speed = 5.0f;
Debug.Log("Oyuncu hizi: " + speed);
}
}Expected output
Oyuncu hizi: 5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which input axis name is used in Unity to read horizontal movement (-1.0 to +1.0)?
- Jump
- Fire1
- Horizontal Correct answer
- Mouse X
Explanation: In Unity's Input Manager, the default horizontal axis is named 'Horizontal' and captures A/D or left/right arrow keys.
2 Translate character transform
transform.____(move * speed * Time.deltaTime);
transform.Translate(move * speed * Time.deltaTime);
Explanation: The 'Translate' method on Transform is invoked to displace an object along a directional vector.
3 Locomotion component concepts
| Term | Meaning |
|---|---|
Input.GetAxis |
Reads keyboard or joystick axis input |
Vector3 |
Direction and position vector in 3D |
Time.deltaTime |
Time elapsed between two frames |
speed |
Multiplier for character movement speed |