Challenge 2: Movement vector
- Game Development course
- Beginner
- Lesson 80/83
- 5 min
Write C# code that builds a movement vector from keyboard input.
Challenge 2: Movement vector
In 3D games, character and object motion is represented via the Vector3 data structure encompassing X, Y, and Z axes. Horizontal and vertical inputs combine to produce a directional vector.
// Converting input axes into a Vector3 movement vector
float h = 1.0f;
float v = 0.0f;
Vector3 direction = new Vector3(h, 0f, v);Multiplying this directional vector by a speed factor yields the object's physical translation.
Practice Print axis coordinates
Define x = 1, y = 0, z = 0 variables. Print Direction: (1, 0, 0) to the console.
Starter code
using System;
class Program
{
static void Main()
{
// x, y, z değişkenlerini tanımlayıp yönü yazdır
}
}Sample solution
using System;
class Program
{
static void Main()
{
int x = 1;
int y = 0;
int z = 0;
Console.WriteLine("Direction: (" + x + ", " + y + ", " + z + ")");
}
}Expected output
Direction: (1, 0, 0)
Practice Print movement and velocity info
Assign "Forward" to direction and 5 to velocity. Print Movement: Forward | Velocity: 5 to the console.
Starter code
using System;
class Program
{
static void Main()
{
// direction ve velocity değerlerini tanımlayıp yazdır
}
}Sample solution
using System;
class Program
{
static void Main()
{
string direction = "Forward";
int velocity = 5;
Console.WriteLine("Movement: " + direction + " | Velocity: " + velocity);
}
}Expected output
Movement: Forward | Velocity: 5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which data type is used in Unity to hold position and direction calculations in 3D space?
- Vector3 Correct answer
- MatrixSingle
- EulerAngle
- Quaternion2D
Explanation: Vector3 is the foundational Unity structure representing 3D coordinates and directions across X, Y, and Z.
2 Instantiate movement vector
Vector3 movement = new ____(horizontal, 0f, vertical);
Vector3 movement = new Vector3(horizontal, 0f, vertical);
Explanation: The Vector3 constructor is called to instantiate a directional vector in 3D space.
3 Movement vector concepts
| Term | Meaning |
|---|---|
Vector3 |
3D position/direction vector (X,Y,Z) |
Input |
Axis signals from keyboard/gamepad |
Velocity |
Direction multiplied by speed value |
Horizontal Axis |
Left/right horizontal movement input |