Skip to content

Lib: Vector2

Guthen edited this page Jun 17, 2019 · 5 revisions

How to use this library ?

You just need to require the vector2.lua like this :

Vector2 = require 'vector2'

Then, you will be able to use the vector2 library.

How does this work ?

Once, the library has been imported, you could use it by creating a Vector2, like this (change the x and y) :

local yourVector2 = Vector( x, y )

Then you should use some functions on it.

Which functions can we use ? (metamethods)

On your created vector2, you could use the following functions :

--  > Functions which return values
yourVector2:GetX() --> return the x value
yourVector2:GetY() --> return the y value
yourVector2:GetSum() --> return the sum of each value (x and y)
yourVector2:Expose() --> return the two values: x; y
yourVector2:Angle() --> return the vector angle
yourVector2:WithinBox( startVector, endVector ) --> return if yourVector2 is inner the box represented by the two others vectors
yourVector2:Dot( v ) --> return the dot product of yourVector2 and v
yourVector2:IsZero() --> return is each field is equal to 0
yourVector2:Lenght() --> return the lenght/magnitude of the vector (can also be get with "#yourVector2")
yourVector2:Distance( v ) --> return the pythagorean distance between two vectors
yourVector2:DistToSqr( v ) --> return the squared distance between two vectors
yourVector2:GetNormal() --> return the normal of the vector
yourVector2:GetOpposite() --> return the opposite of this vector

--  > Functions which modify
yourVector2:SetX( x ) --> change the x value
yourVector2:SetY( y ) --> change the y value
yourVector2:Zero() --> set each field to 0
yourVector2:Normalize() --> normalize the vector 
yourVector2:Opposite() --> set the vector as its opposite

Can we add/sub/multiply/divise Vector2 together ?

Yes, you can add, sub, multiply, divise vector2 (exception to modulo, which you can't). It should look like that :

-- add
print( Vector2( 500, 10 ) + Vector2( 100, 45 ) ) -- > x: 600; y: 55
-- sub
print( Vector2( 500, 10 ) - Vector2( 100, 45 ) ) -- > x: 400; y: -35
-- multiply
print( Vector2( 500, 10 ) * Vector2( 100, 45 ) ) -- > x: 50000; y: 450
-- divise
print( Vector2( 500, 10 ) / Vector2( 100, 45 ) ) -- > x: 5; y: 0