2D Vectors

Luanti stores 2-dimensional vectors in Lua as tables of 2 coordinates, and has a class to represent them (vector2.*).

The API provides vector2.new to create vectors:

  • vector2.new(x, y)
  • {x=num, y=num} (Even here you are still supposed to use vector2.new.)

Compatibility notes

Vectors should be created using vector2.new(x, y) to ensure they have the proper metatable. This enables:

  • Method call syntax (e.g., v:length() instead of vector2.length(v))
  • Operator overloading (e.g., v1 + v2 instead of vector2.add(v1, v2))
  • Type checking with vector2.check()

Special properties of the class

For special properties common to all vector types (indexing, method syntax, operators, etc.), see Common to all vector types.

Functions

For common functions available to both vector and vector2, see Common functions.

The following functions are specific to vector2 (2D vectors).

For the following functions, v, v1, v2 are vectors, p1, p2 are position vectors, s is a scalar (a number), vectors are written like this: (x, y):

  • vector2.new(x, y):
    • Returns a new vector (x, y).
  • vector2.from_angle(angle):
    • Returns a new unit vector from an angle.
    • angle is the angle in radians from the positive x-axis (counterclockwise).
    • Example: vector2.from_angle(math.pi / 2) returns a vector pointing up (0, 1).
  • vector2.to_angle(v):
    • Returns the angle of the vector in radians.
    • angle is the angle from the positive x-axis (counterclockwise), in the range (-pi, pi].
    • The edge case of (0, 0) returns 0.
    • Example: vector2.to_angle(vector2.new(0, 1)) returns math.pi / 2.
  • vector2.sort(v1, v2):
    • Returns in order minp, maxp vectors of the rectangle defined by v1, v2.
  • vector2.angle(v1, v2):
    • Returns the angle between v1 and v2 in radians.
    • This is always a positive value (unsigned angle).
  • vector2.rotate(v, angle):
    • Returns a new vector rotated counterclockwise by angle radians around the origin.
    • The length of the vector is preserved.
    • Example: vector2.rotate(vector2.new(1, 0), math.pi / 2) returns (0, 1).
  • vector2.offset(v, x, y):
    • Returns the sum of the vectors v and (x, y).

Operators

For vector operators (+, -, *, /, ==, unary -), see Common to all vector types.