UNPKG

@rawify/vector2

Version:

The RAW JavaScript 2D Vector library

14 lines (12 loc) 2.71 kB
/* Vector2 v0.0.3 8/2/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 d(a,b){const c=Object.create(e.prototype);c.x=a;c.y=b;return c}function e(a,b){let c=this instanceof e?this:Object.create(e.prototype);"object"===typeof a?a instanceof Array?(c.x=a[0],c.y=a[1]):(c.x=a.x,c.y=a.y):isNaN(a)||isNaN(b)||(c.x=a,c.y=b);return c}e.prototype={x:0,y:0,add:function(a){return d(this.x+a.x,this.y+a.y)},sub:function(a){return d(this.x-a.x,this.y-a.y)},neg:function(){return d(-this.x,-this.y)},scale:function(a){return d(this.x*a,this.y*a)},prod:function(a){return d(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 d(-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 d(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 d(-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 d(a.x*b-this.x,a.y*b-this.y)},refract:function(a,b){const c=this.dot(a);var f= 1-b*b*(1-c*c);if(0>f)return null;f=Math.sqrt(f);return d(b*this.x-(b*c+f)*a.x,b*this.y-(b*c+f)*a.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:d(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 d(b*this.x-a*this.y,a*this.x+b*this.y)},apply:function(a,b={x:0,y:0}){return d(a(this.x,b.x),a(this.y,b.y))},toArray:function(){return[this.x,this.y]},clone:function(){return d(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 d(this.x+b*(a.x-this.x), this.y+b*(a.y-this.y))},toString:function(){return"("+this.x+", "+this.y+")"}};e.random=function(){return d(Math.random(),Math.random())};e.fromPoints=function(a,b){return d(b.x-a.x,b.y-a.y)};e.fromBarycentric=function(a,b,c,f,h){const g=a.x;a=a.y;return d(g+(b.x-g)*f+(c.x-g)*h,a+(b.y-a)*f+(c.y-a)*h)};"function"===typeof define&&define.amd?define([],function(){return e}):"object"===typeof exports?(Object.defineProperty(e,"__esModule",{value:!0}),e["default"]=e,e.Vector2=e,module.exports=e):k.Vector2= e})(this);