Represents a 2D vector and provides static methods for vector calculations.

const v1 = new Vector2(2, 1);
const v2 = new Vector2(3, 2);
const v3 = new Vector2(); // zero vector

Vector2.add(v3, v1, v2);
v3.x // 5
v3.y // 3

Constructors

Accessors

  • get magnitude(): number
  • Get the magnitude of the vector

    Returns number

    The magnitude of the vector

Methods

  • Get the distance with another vector

    Parameters

    • vector: Vector2

      The vector to compare

    Returns number

    The magnitude of the distance

  • Compare if two vector are equals

    Parameters

    • vector: Vector2

      The vector to compare

    Returns boolean

    True if the vectors are equals, false if not

  • Set the vector

    Parameters

    • x: number

      The x value

    • y: number

      The y value

    Returns void

  • Calculates a + b

    Parameters

    Returns Vector2

    The output vector

    const v1 = new Vector2(2, 1);
    const v2 = new Vector2(3, 2);
    const v3 = Vector2.add(new Vector2(), v1, v2);
    v3.x // 5
    v3.y // 3
  • Calculates the cross product of two vectors and returns a scalar value

    Parameters

    Returns number

    The cross produc result

    const v1 = new Vector2(3, 2);
    const v2 = new Vector2(2, 1);
    Vector2.cross(v1, v2); // -1
  • Calculates the dot product of two vectors and returns a scalar value

    Parameters

    Returns number

    The dot product result

    const v1 = new Vector2(3, 2);
    const v2 = new Vector2(2, 1);
    Vector2.dot(v1, v2); // 8
  • Normalize a vector

    Parameters

    Returns Vector2

    The output vector

    const v1 = new Vector2(0, 2);
    const v2 = Vector2.normal(new Vector2(), v1);
    v2.x // -2
    v2.y // 0
  • Rounds a vector

    Parameters

    Returns Vector2

    The output vector

    const v1 = new Vector2(3.9, 2.2);
    const v2 = Vector2.round(new Vector2(), v1);
    v2.x // 4
    v2.y // 2
  • Scale a vector

    Parameters

    • out: Vector2

      The output vector

    • a: Vector2

      The vector to scale

    • scalar: number

      The scalar value

    Returns Vector2

    The output vector

    const v1 = new Vector2(3, 2);
    const v2 = Vector2.scale(new Vector2(), v1, 2);
    v2.x // 6
    v2.y // 4
  • Calculates a - b

    Parameters

    Returns Vector2

    The output vector

    const v1 = new Vector2(3, 2);
    const v2 = new Vector2(2, 1);
    const v3 = Vector2.subtract(new Vector2(), v1, v2);
    v3.x // 1
    v3.y // 1
  • Returns the unit vector

    Parameters

    Returns Vector2

    The output vector

    const v1 = new Vector2(3, 0);
    const v2 = Vector2.unit(new Vector2(), v1);
    v2.x // 1
    v2.y // 0