Skip to content

Instantly share code, notes, and snippets.

@abs-js
Created August 2, 2024 19:13
Show Gist options
  • Select an option

  • Save abs-js/96fddc0a09a5afd6729d94a6ab6309ce to your computer and use it in GitHub Desktop.

Select an option

Save abs-js/96fddc0a09a5afd6729d94a6ab6309ce to your computer and use it in GitHub Desktop.
VECTOR3 is an open source library for anyone using 3D design with JavaScript. Even if it is small, it can help your code to use fewer characters to calculate a normalized vector, for example. Go deeper and you will definitely find it interesting (be honest :P).

VECTOR3

VECTOR3 is an open source library for anyone using 3D design with JavaScript. Even if it is small, it can help your code to use fewer characters to calculate a normalized vector, for example. Go deeper and you will definitely find it interesting (be honest :P).

ALL functions

* normalizes vectors
* calculates the dot product
* add/subtract (necessary, right?)
* simplifies in directions (you can doubt as many times as you want :D)

usage

creating one vector

You can create a vector simply using vector3(vector):

const vector = vector3({
    x: 1, // x
    Y: 1, // y
    z: -1, // z
});

vector.vector // return the vector 1, 1, -1

normalize

use vector.normalized:

vector.normalized;
// Object { x: 0.5773502691896258, y: 0.5773502691896258, z: -0.5773502691896258 }

dot product

use the function vector.dot(v) where v is another vector:

vector.dot({x: -2, y: -3, z: -5});
// 0 (are perpendicular)

add/subtract

use vector.add or vector.subtract, with one vector in the argument

vector.subtract({ x: 1, y: 2, z: 3 }); // exit: (0, -1, -4)
vector.add({ x: 1, y: 2, z: 3 }); // exit: (2, 3, 2)

CREDITS

made in brazil i'm, artur bernardo, beginer in english and JavaScript, I'd rather help everyone than keep to myself, even if they're gangsters

function vector3(vec) {if (vec.x === undefined || vec.y === undefined || vec.z === undefined) {throw new Error("Vector must have x, y, and z components");}const magnitude = Math.sqrt(vec.x * vec.x + vec.y * vec.y + vec.z * vec.z);if (magnitude === 0) {throw new Error("Cannot normalize a zero vector");}const normalized = {x: vec.x / magnitude,y: vec.y / magnitude,z: vec.z / magnitude};function simplifyComponent(value) {if (value > 0) return 1;if (value < 0) return -1;return 0;return {vector: vec,normalized: normalized,dot: function(vec2) {return (vec.x * vec2.x) + (vec.y * vec2.y) + (vec.z * vec2.z);},add: function(vec2) {return {x: vec.x + vec2.x,y: vec.y + vec2.y,z: vec.z + vec2.z};},subtract: function(vec2) {return {x: vec.x - vec2.x,y: vec.y - vec2.y,z: vec.z - vec2.z};},simplify: {x: simplifyComponent(vec.x),y: simplifyComponent(vec.y),z: simplifyComponent(vec.z)}};}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment