UNPKG

@mousepox/math

Version:

Math-related objects and utilities

70 lines (69 loc) 1.84 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Vector2 = void 0; const core_1 = require("./core"); class Vector2 { constructor(x = 0, y = 0) { this.x = x; this.y = y; } static fromAngle(radians) { return new Vector2(Math.cos(radians), Math.sin(radians)); } get angle() { return Math.atan2(this.y, this.x); } get magnitude() { return Math.sqrt(this.x * this.x + this.y * this.y); } set(x, y) { this.x = x; this.y = y; return this; } add(p) { this.x += p.x; this.y += p.y; return this; } copy(p) { this.x = p.x; this.y = p.y; return this; } normalize() { const mag = this.magnitude; if (mag === 0) { return this; } else { return this.scale(1 / mag); } } scale(n) { this.x *= n; this.y *= n; return this; } subtract(p) { this.x -= p.x; this.y -= p.y; return this; } constrain(x, y, width, height) { this.x = (0, core_1.clamp)(this.x, x, x + width); this.y = (0, core_1.clamp)(this.y, y, y + height); return this; } rotate(angle, origin) { var _a, _b; const ox = (_a = origin === null || origin === void 0 ? void 0 : origin.x) !== null && _a !== void 0 ? _a : 0; const oy = (_b = origin === null || origin === void 0 ? void 0 : origin.y) !== null && _b !== void 0 ? _b : 0; const cos = Math.cos(angle); const sin = Math.sin(angle); const x = (this.x - ox) * cos - (this.y - oy) * sin + ox; const y = (this.x - ox) * sin + (this.y - oy) * cos + oy; return this.set(x, y); } } exports.Vector2 = Vector2;