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 usevector2.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 ofvector2.length(v)) - Operator overloading (e.g.,
v1 + v2instead ofvector2.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).
- Returns a new vector
vector2.from_angle(angle):- Returns a new unit vector from an angle.
angleis 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.
angleis the angle from the positive x-axis (counterclockwise), in the range(-pi, pi].- The edge case of
(0, 0)returns0. - Example:
vector2.to_angle(vector2.new(0, 1))returnsmath.pi / 2.
vector2.sort(v1, v2):- Returns in order minp, maxp vectors of the rectangle defined by
v1,v2.
- Returns in order minp, maxp vectors of the rectangle defined by
vector2.angle(v1, v2):- Returns the angle between
v1andv2in radians. - This is always a positive value (unsigned angle).
- Returns the angle between
vector2.rotate(v, angle):- Returns a new vector rotated counterclockwise by
angleradians around the origin. - The length of the vector is preserved.
- Example:
vector2.rotate(vector2.new(1, 0), math.pi / 2)returns(0, 1).
- Returns a new vector rotated counterclockwise by
vector2.offset(v, x, y):- Returns the sum of the vectors
vand(x, y).
- Returns the sum of the vectors
Operators¶
For vector operators (+, -, *, /, ==, unary -), see Common to all vector types.