2d-physics-engine
Version:
A lightweight, flexible 2D physics engine with ECS architecture, built with TypeScript
89 lines • 2.99 kB
JavaScript
export class Vector2 {
constructor(x = 0, y = 0) {
Object.defineProperty(this, "x", {
enumerable: true,
configurable: true,
writable: true,
value: x
});
Object.defineProperty(this, "y", {
enumerable: true,
configurable: true,
writable: true,
value: y
});
}
/** Returns the magnitude (length) of the vector. */
getMagnitude() {
return Math.hypot(this.x, this.y);
}
/** Returns the squared magnitude (more performant for comparisons). */
getSquareMagnitude() {
return this.x * this.x + this.y * this.y;
}
/** Returns a normalized vector (unit length). */
getNormal() {
const mag = this.getMagnitude();
return mag > 0 ? new Vector2(this.x / mag, this.y / mag) : Vector2.zero();
}
/** Returns a vector perpendicular to this one (rotated 90°). */
getTangent() {
return new Vector2(-this.y, this.x);
}
/** Scales the vector by the given scalar. */
scale(scalar) {
return new Vector2(this.x * scalar, this.y * scalar);
}
/** Returns a new vector representing this + other. */
add(other) {
return new Vector2(this.x + other.x, this.y + other.y);
}
/** Returns a new vector representing this - other. */
subtract(other) {
return new Vector2(this.x - other.x, this.y - other.y);
}
/** Returns a new vector representing this + other * scalar. */
addScaled(other, scalar) {
return new Vector2(this.x + other.x * scalar, this.y + other.y * scalar);
}
/** Angle in radians between two vectors. */
radians(other) {
const magProduct = this.getMagnitude() * other.getMagnitude();
if (magProduct === 0)
return 0; // prevent NaN
let cos = this.dotProduct(other) / magProduct;
// Clamp floating point errors
cos = Math.min(1, Math.max(-1, cos));
return Math.acos(cos);
}
/** Component-wise multiplication. */
componentProduct(other) {
return new Vector2(this.x * other.x, this.y * other.y);
}
/** Scalar dot product. */
dotProduct(other) {
return this.x * other.x + this.y * other.y;
}
/** Scalar 2D cross product. */
crossProduct(other) {
return this.x * other.y - this.y * other.x;
}
/** Rotates the vector by given radians. */
rotate(radian) {
const cos = Math.cos(radian);
const sin = Math.sin(radian);
return new Vector2(this.x * cos - this.y * sin, this.x * sin + this.y * cos);
}
/** Returns a copy of this vector. */
clone() {
return new Vector2(this.x, this.y);
}
/** Static shorthand constructors. */
static zero() {
return new Vector2(0, 0);
}
static fromAngle(radian) {
return new Vector2(Math.cos(radian), Math.sin(radian));
}
}
//# sourceMappingURL=Vector2.js.map