UNPKG

@rawify/vector2

Version:

The RAW JavaScript 2D Vector library

13 lines (11 loc) 2.56 kB
/* Vector2 v0.0.2 3/26/2025 https://github.com/rawify/Vector2.js Copyright (c) 2025, Robert Eisele (https://raw.org/) Licensed under the MIT license. */ 'use strict';(function(k){function c(a,b){const e=Object.create(d.prototype);e.x=a;e.y=b;return e}function d(a,b){let e=this instanceof d?this:Object.create(d.prototype);"object"===typeof a?a instanceof Array?(e.x=a[0],e.y=a[1]):(e.x=a.x,e.y=a.y):isNaN(a)||isNaN(b)||(e.x=a,e.y=b);return e}d.prototype={x:0,y:0,add:function(a){return c(this.x+a.x,this.y+a.y)},sub:function(a){return c(this.x-a.x,this.y-a.y)},neg:function(){return c(-this.x,-this.y)},scale:function(a){return c(this.x*a,this.y*a)},prod:function(a){return c(this.x* a.x,this.y*a.y)},dot:function(a){return this.x*a.x+this.y*a.y},cross:function(a){return this.x*a.y-this.y*a.x},perp:function(){return c(-this.y,this.x)},projectTo:function(a){const b=(this.x*a.x+this.y*a.y)/(a.x*a.x+a.y*a.y);return c(a.x*b,a.y*b)},rejectFrom:function(a){const b=(this.y*a.x-this.x*a.y)/(a.x*a.x+a.y*a.y);return c(-a.y*b,a.x*b)},reflect:function(a){const b=2*(this.y*a.y+this.x*a.x)/(a.x*a.x+a.y*a.y);return c(a.x*b-this.x,a.y*b-this.y)},angle:function(){return Math.atan2(this.y,this.x)}, norm:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},norm2:function(){return this.x*this.x+this.y*this.y},normalize:function(){const a=this.norm();return 0===a||1===a?this:c(this.x/a,this.y/a)},distance:function(a){const b=this.x-a.x;a=this.y-a.y;return Math.sqrt(b*b+a*a)},set:function(a){this.x=a.x;this.y=a.y},rotate:function(a){const b=Math.cos(a);a=Math.sin(a);return c(b*this.x-a*this.y,a*this.x+b*this.y)},apply:function(a,b={x:0,y:0}){return c(a(this.x,b.x),a(this.y,b.y))},toArray:function(){return[this.x, this.y]},clone:function(){return c(this.x,this.y)},equals:function(a){return this===a||1E-13>Math.abs(this.x-a.x)&&1E-13>Math.abs(this.y-a.y)},isParallel:function(a){return 1E-13>Math.abs(this.cross(a))},isUnit:function(){return 1E-13>Math.abs(this.x*this.x+this.y*this.y-1)},lerp:function(a,b){return c(this.x+b*(a.x-this.x),this.y+b*(a.y-this.y))},toString:function(){return"("+this.x+", "+this.y+")"}};d.random=function(){return c(Math.random(),Math.random())};d.fromPoints=function(a,b){return c(b.x- a.x,b.y-a.y)};d.fromBarycentric=function(a,b,e,g,h){const f=a.x;a=a.y;return c(f+(b.x-f)*g+(e.x-f)*h,a+(b.y-a)*g+(e.y-a)*h)};"function"===typeof define&&define.amd?define([],function(){return d}):"object"===typeof exports?(Object.defineProperty(d,"__esModule",{value:!0}),d["default"]=d,d.Vector2=d,module.exports=d):k.Vector2=d})(this);