72 lines
2.1 KiB
JavaScript
72 lines
2.1 KiB
JavaScript
export class Vector2 {
|
|
x;
|
|
y;
|
|
constructor(x, y) {
|
|
this.x = x;
|
|
this.y = y;
|
|
}
|
|
static lerp(a, b, t) {
|
|
return a.multiplyScalar(1 - t).add(b.multiplyScalar(t));
|
|
}
|
|
add(vector) {
|
|
return new Vector2(this.x + vector.x, this.y + vector.y);
|
|
}
|
|
subtract(vector) {
|
|
return new Vector2(this.x - vector.x, this.y - vector.y);
|
|
}
|
|
multiplyScalar(scalar) {
|
|
return new Vector2(this.x * scalar, this.y * scalar);
|
|
}
|
|
dot(vector) {
|
|
return this.x * vector.x + this.y * vector.y;
|
|
}
|
|
cross(vector) {
|
|
return this.x * vector.y - this.y * vector.x;
|
|
}
|
|
magnitude() {
|
|
return Math.sqrt(this.x * this.x + this.y * this.y);
|
|
}
|
|
normalized() {
|
|
const magnitude = this.magnitude();
|
|
if (magnitude === 0) {
|
|
throw new Error("Cannot normalize a vector with magnitude 0");
|
|
}
|
|
return this.multiplyScalar(1 / magnitude);
|
|
}
|
|
distance(vector) {
|
|
return Math.sqrt((this.x - vector.x) ** 2 + (this.y - vector.y) ** 2);
|
|
}
|
|
distanceSquared(vector) {
|
|
return (this.x - vector.x) ** 2 + (this.y - vector.y) ** 2;
|
|
}
|
|
limit(max) {
|
|
const magnitude = this.magnitude();
|
|
if (magnitude > max) {
|
|
return this.normalized().multiplyScalar(max);
|
|
}
|
|
return this;
|
|
}
|
|
angle() {
|
|
return Math.atan2(this.y, this.x);
|
|
}
|
|
angleBetween(vector) {
|
|
const dotProd = this.dot(vector);
|
|
const magnitudes = this.magnitude() * vector.magnitude();
|
|
if (magnitudes === 0) {
|
|
throw new Error("Cannot calculate angle with a zero-magnitude vector");
|
|
}
|
|
return Math.acos(dotProd / magnitudes);
|
|
}
|
|
clone() {
|
|
return new Vector2(this.x, this.y);
|
|
}
|
|
equals(vector) {
|
|
return this.x === vector.x && this.y === vector.y;
|
|
}
|
|
rotate(angle) {
|
|
const cos = Math.cos(angle);
|
|
const sin = Math.sin(angle);
|
|
return new Vector2(this.x * cos - this.y * sin, this.x * sin + this.y * cos);
|
|
}
|
|
}
|
|
//# sourceMappingURL=Vector2.js.map
|