Vector2

Overview

Description

The Vector2 class represents a mathematical 2D vector with x and y components. It is commonly used in game development or graphical applications for 2D position, direction, and mathematical operations.

Properties

X

number The x-coordinate of the vector.

Code Samples

local myVector = Vector2.new(5, 10)
print(myVector.X)  -- Output: 5

Y

number The y-coordinate of the vector.

Code Samples

local myVector = Vector2.new(5, 10)
print(myVector.Y)  -- Output: 10

zero

Vector2 A vector whose x and y components are both zero. Typically used to represent the origin or a null vector.

Code Samples

local zeroVector = Vector2.zero
print(zeroVector.X, zeroVector.Y)  -- Output: 0, 0

one

Vector2 A vector whose x and y components are both set to 1.

Code Samples

local oneVector = Vector2.one
print(oneVector.X, oneVector.Y)  -- Output: 1, 1

xAxis

Vector2 A unit vector pointing in the x-axis direction (1, 0).

Code Samples

local xUnitVector = Vector2.xAxis
print(xUnitVector.X, xUnitVector.Y)  -- Output: 1, 0

yAxis

Vector2 A unit vector pointing in the y-axis direction (0, 1).

Code Samples

local yUnitVector = Vector2.yAxis
print(yUnitVector.X, yUnitVector.Y)  -- Output: 0, 1

Constructors

new

Creates a new instance of the Vector2 class with given x and y components.

Parameters

number x

The x-coordinate of the vector.

number y

The y-coordinate of the vector.

Return

Vector2

A new vector with the specified x and y coordinates.

Code Samples

local myVector = Vector2.new(3, 7)
print(myVector.X, myVector.Y)  -- Output: 3, 7

Methods

Add

Adds two vectors and returns the result.

Parameters

Vector2 other

The vector to add.

Return

Vector2

The result of vector addition.

Code Samples

local vectorA = Vector2.new(2, 3)
local vectorB = Vector2.new(4, 1)
local result = vectorA:Add(vectorB)
print(result.X, result.Y)  -- Output: 6, 4

Subtract

Subtracts another vector from this vector.

Parameters

Vector2 other

The vector to subtract.

Return

Vector2

The result of vector subtraction.

Code Samples

local vectorA = Vector2.new(6, 4)
local vectorB = Vector2.new(3, 1)
local result = vectorA:Subtract(vectorB)
print(result.X, result.Y)  -- Output: 3, 3

Multiply

Multiplies the components of the vector by a scalar value.

Parameters

number scalar

The scalar value to multiply with.

Return

Vector2

The scaled vector.

Code Samples

local vector = Vector2.new(2, 3)
local result = vector:Multiply(2)
print(result.X, result.Y)  -- Output: 4, 6

Magnitude

Calculates the magnitude (length) of the vector.

Return

number

The magnitude of the vector.

Code Samples

local vector = Vector2.new(3, 4)
print(vector:Magnitude())  -- Output: 5

Normalize

Normalizes the vector (makes it a unit vector).

Return

Vector2

The normalized vector.

Code Samples

local vector = Vector2.new(3, 4)
local normalized = vector:Normalize()
print(normalized.X, normalized.Y)  -- Output: 0.6, 0.8

Last updated