@mousepox/math
Version:
Math-related objects and utilities
67 lines (66 loc) • 1.52 kB
JavaScript
import { clamp } from "./core";
export class Vector2 {
static fromAngle(radians) {
return new Vector2(Math.cos(radians), Math.sin(radians));
}
x;
y;
get angle() {
return Math.atan2(this.y, this.x);
}
get magnitude() {
return Math.sqrt(this.x * this.x + this.y * this.y);
}
constructor(x = 0, y = 0) {
this.x = x;
this.y = 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 = clamp(this.x, x, x + width);
this.y = clamp(this.y, y, y + height);
return this;
}
rotate(angle, origin) {
const ox = origin?.x ?? 0;
const oy = origin?.y ?? 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);
}
}