2D and 3D Vector classes for game development and physics simulations.
Install via npm
npm install @coderosh/vector
Or via yarn
yarn add @coderosh/vector
import { Vector2D, Vector3D } from '@coderosh/vector'
/* 3D Vector */
new Vector3D(1, 4, 1)
/* 2D Vector */
new Vector2D(1, 3)
- add - 2D and 3D
- sub - 2D and 3D
- scale - 2D and 3D
- lerp - 2D and 3D
- slerp - 3D only
- nlerp - 2D and 3D
- lenSqr - 2D and 3D
- len - 2D and 3D
- dist - 2D and 3D
- normalize - 2D and 3D
- equals - 2D and 3D
- copy - 2D and 3D
- dot - 2D and 3D
- cross - 3D only
Adds two vectors
const vec3d = new Vector3D(1, 2, 3)
vec3d.add(4, 5, 6)
vec3d.add(new Vector3D(4, 5, 6))
const vec2d = new Vector2D(1, 2)
vec2d.add(4, 5)
vec2d.add(new Vector2D(4, 5))
Substracts two vectors
const vec3d = new Vector3D(1, 2, 3)
vec3d.sub(4, 5, 6)
vec3d.sub(new Vector3D(4, 5, 6))
const vec2d = new Vector2D(1, 2)
vec2d.sub(4, 5)
vec2d.sub(new Vector2D(4, 5))
Multiply a vector by a scalar factor
const vec3d = new Vector3D(1, 2, 3)
vec3d.scale(2)
const vec2d = new Vector2D(1, 2)
vec2d.scale(2)
Square of length of vector
const vec3d = new Vector3D(1, 2, 3)
vec3d.lenSqr()
const vec2d = new Vector2D(1, 2)
vec2d.lenSqr()
Length of vector
const vec3d = new Vector3D(1, 2, 3)
vec3d.len()
const vec2d = new Vector2D(1, 2)
vec2d.len()
Normalize the vector
const vec3d = new Vector3D(1, 2, 3)
vec3d.normalize()
const vec2d = new Vector2D(1, 2)
vec2d.normalize()
Calculate distance between two vectors
const vec3d = new Vector3D(1, 2, 3)
vec3d.dist(5, 2, 3)
vec3d.dist(new Vector3D(5, 2, 3))
const vec2d = new Vector2D(1, 2)
vec2d.dist(5, 2)
vec2d.dist(new Vector2D(5, 2))
Check if two vectors have same coordinates
const vec3d = new Vector3D(1, 2, 3)
vec3d.equals(1, 2, 3)
vec3d.equals(new Vector3D(1, 2, 3))
const vec2d = new Vector2D(1, 2)
vec2d.equals(1, 2)
vec2d.equals(new Vector2D(1, 2))
Returns dot product of two vectors
const vec3d = new Vector3D(1, 2, 3)
vec3d.dot(1, 1, 2)
vec3d.dot(new Vector3D(1, 1, 2))
const vec2d = new Vector2D(1, 2)
vec2d.dot(4, 2)
vec2d.dot(new Vector2D(4, 2))
Returns cross product of two vectors
const vec = new Vector3D(1, 2, 3)
vec.cross(1, 2, 4)
vec.cross(new Vector3D(1, 2, 4))
Linear interpolate vectors
const vec3d = new Vector3D(1, 2, 3)
vec3d.lerp(1, 1, 2, 0.1)
vec3d.lerp(new Vector3D(1, 1, 2), 0.1)
const vec2d = new Vector2D(1, 2)
vec2d.lerp(4, 2, 0.1)
vec2d.lerp(new Vector2D(4, 2), 0.1)
Spherical linear interpolate vectors
const vec = new Vector3D(1, 0, 0)
vec.slerp(new Vector3D(0, 1, 0), 0.5)
vec.slerp(0, 1, 0, 0.5)
Linear interpolate vectors and normalize
const vec3d = new Vector3D(1, 2, 3)
vec3d.nlerp(1, 1, 2, 0.1)
vec3d.nlerp(new Vector3D(1, 1, 2), 0.1)
const vec2d = new Vector2D(1, 2)
vec2d.nlerp(4, 2, 0.1)
vec2d.nlerp(new Vector2D(4, 2), 0.1)
const vec3d = new Vector3D(1, 2, 3)
const newVec3d = vec3d.copy()
const newVec3d_ = new Vector(vec3d)
const vec2d = new Vector3D(1, 2, 3)
const newVec2d = vec2d.copy()
const newVec2d_ = new Vector(vec2d)
MIT