Game Development
Movement vector
Learn to turn axis inputs into a movement Vector3.
Combining Axes with Vector3
In character movement, horizontal and vertical axis inputs are combined into a Vector3 variable. The horizontal axis (X) controls left/right movement, while the vertical axis (Z) controls forward/backward movement in a 3D world. The Y axis is typically reserved for gravity and jumping.
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = new Vector3(x, 0f, z);
Applying the Movement Vector
The constructed movement vector is applied to the object using the previously learned transform.Translate method. Multiplying by a speed variable adjusts the movement rate. This allows the object to move smoothly according to the keys pressed by the player.
Vector3 move = new Vector3(x, 0f, z);
transform.Translate(move * speed * Time.deltaTime);
Exercise Calculate Movement Vector
Take Input.GetAxis("Horizontal") and Input.GetAxis("Vertical"), combine them with new Vector3(yatay, 0f, dikey). Print the result using Debug.Log(hareket);.
Show example solution
using System;
public struct Vector3
{
public float x, y, z;
public Vector3(float x, float y, float z) { this.x = x; this.y = y; this.z = z; }
public override string ToString() => $"({x}, {y}, {z})";
}
public static class Input
{
public static float GetAxis(string axis) => axis == "Horizontal" ? 1.0f : 2.0f;
}
public static class Debug
{
public static void Log(object message) => Console.WriteLine(message);
}
public class Program
{
public static void Main()
{
float yatay = Input.GetAxis("Horizontal");
float dikey = Input.GetAxis("Vertical");
Vector3 hareket = new Vector3(yatay, 0f, dikey);
Debug.Log(hareket);
}
}
Test yourself
-
In a 3D game, which Vector3 component is mapped to axis input for moving forward and backward on the ground?
- W component
- X component
- Y component
- Z component
Show answer
Z component — In 3D space, X is horizontal (right-left), Y is vertical height (up-down), and Z is depth (forward-backward).
-
Create 3D Movement Vector
Vector3 hareket = new ____(yatay, 0f, dikey);
Show answer
Vector3 hareket = new Vector3(yatay, 0f, dikey);
-
Vector Components Matching
- Vector3.x
- Right and left horizontal axis input
- Vector3.y
- Height and jumping axis
- Vector3.z
- Forward and backward depth axis
- transform.Translate
- Translates object in vector direction
Next lesson: Summary - Input