Vector

JunDev·2025년 3월 10일

Unity

목록 보기
3/8

What is Vector?

A Vector is a mathematical object that represents a direction and/or magnitude (length) in 2D or 3D space. Vectors are used extensively in Unity to handle positions, directions, velocities, and other spatial operations. Unity provides several vector types to represent these in different dimensions.

Common Types of Vectors in Unity:

Vector2 – Represents a 2D vector (x, y) for 2D space (e.g., for 2D games or UI positioning).

  • Example: Vector2(3, 4)
  • Can be used for 2D movement, collision detection, etc.

Vector3 – Represents a 3D vector (x, y, z) for 3D space (e.g., for 3D game objects' positions or directions).

  • Example: Vector3(1, 2, 3)
  • Commonly used for movement, positioning, scaling, and rotation in 3D games.

Vector4 – Represents a 4D vector (x, y, z, w), used in more advanced cases like shaders, 3D transformations with homogenous coordinates, and some mathematical operations.

  • Example: Vector4(1, 2, 3, 4)
  • Less common in regular gameplay, often used for specialized tasks.

Adding and Subtracting Vectors

Vector3 v1 = new Vector3(1, 0, 0);
Vector3 v2 = new Vector3(0, 1, 0);
Vector3 result = v1 + v2;  // (1, 1, 0)
Vector3 v1 = new Vector3(2, 3, 4);
Vector3 v2 = new Vector3(1, 1, 1);
Vector3 result = v1 - v2;  // (1, 2, 3)

Common Usage

  • Positioning: Objects in the game world are positioned using Vector3 (e.g., transform.position = new Vector3(0, 1, 0);).

  • Movement: Moving an object in a particular direction, like transform.Translate(Vector3.right speed Time.deltaTime);.

  • Direction and Rotation: Vectors are often used to represent directions for things like look rotation (transform.forward) or velocity.

  • Physics: Vectors are crucial in Unity's physics system (e.g., rigidbody.velocity, force, etc.).

void Update()
{
    // Move the object up
    transform.position += Vector3.up * speed * Time.deltaTime;
}
profile
Jun's Dev Journey

0개의 댓글