This library was made by me because I wasn't happy with other vector libraries for Lua. Functions largely based on the PVector class from Processing, and the code syntax was helped by reference to HUMP's Vector class.
If you encounter any issues or bugs, raise an issue on Github or even make a pull request if you're a real trooper.
Put the vector.lua file into your project and require it:
local vector = require("vector")
local vector = require("vector")
v = vector(100, 100) -- you can also use vector.new()
print(v) -- will print "(100, 100)"
-- do some cool stuff with vectors!
Returns a new Vector
object with the given x and y values, or 0 if not given. You can also simply call vector()
, that being whatever you've chosen to name the module.
Similar to vector.new
, but returns a Vector
which is pointing in a random direction.
Creates a new Vector
from an angle in radians. Note: the y value of the vector is flipped from normal, since this library is specifically geared toward game development. Feel free to remove the -
in fromAngle
if you need to.
Sets the x and y values of the used Vector
. Either one can be nil
, in which case, the value will not change.
Replaces the x
and y
values of the current vector to the x
and y
values of the given vector. Mostly used in other functions but I'm sure someone can find a use for it.
Returns a copy of the used Vector
.
Returns the magnitude of the Vector
.
Returns the squared magnitude of the Vector
.
Sets the magnitude of the Vector
to mag
. In reality, this normalizes the Vector
and multiplies it by mag
.
Returns the two-dimensional distance between vector a and vector b.
Returns the dot product of the two Vector
s.
Normalizes the Vector
. In other words, it sets it's magnitude to 1.
Limits the magnitude of the Vector
. If it's current magnitude is greater than max
, it sets the magnitude to max
.
Returns the angle of rotation of the Vector
.
Rotates the Vector
by theta
, which is in radians.
Returns an array version of the vector. For example, vector(50, 60):unpack()
would return {50, 60}
Returns both the x and y values unpacked. Useful for function arguments. For example, vector(50,60):unpack()
would return 50, 60
You can add, subtract, multiply, divide, and compare vectors using the basic syntax. If you don't know how meta functions work, check this out.
a = vector(50, 25)
b = vector(25, 50)
-a
Would return (-50, -25) in this case.
a + b
Would return (75, 75) in this case.
a - b
Would return (25, -25) in this case.
a * b
Would return (1250, 1250) in this case.
a * 2
Would return (100, 50) in this case.
a / b
Would return (2, 0.5) in this case.
a == b
Would return false.
vector(107,6) == vector(107,6)
Would return true.
You can also easily get a human-readable string representation of the vector.
print(a)
Would print "(50, 25)"
tostring(b)
Would return "(25, 50)"