@game-vir/entity
Version:
Entity system for game development.
51 lines (50 loc) • 1.91 kB
JavaScript
import { round } from '@augment-vir/common';
import { Angle } from './angle.js';
/**
* A vector (combination of magnitude and angle) definition. This can be defined in the following
* ways:
*
* - `Vector.fromPoints()`
* - `Vector.fromComponents()`
* - `new Vector()`
*
* @category Math
*/
export class Vector {
angle;
options;
/** Create a new Vector instance by calculating the distance and angle between two points. */
static fromPoints(point1, point2, options) {
const dx = point2.x - point1.x;
const dy = point2.y - point1.y;
return Vector.fromComponents({ x: dx, y: dy }, options);
}
/** Create a new Vector instance from its X and Y components. */
static fromComponents({ x, y }, options) {
const radians = Math.atan2(y, x);
return new Vector(Math.hypot(x, y), new Angle({ radians }, options), options);
}
/** The vector's distance in its given angle. (This can be modified after Vector construction.) */
magnitude;
constructor(
/** The vector's original magnitude. (This can be modified after Vector construction.) */
magnitude,
/** The vector's original angle. (This can be modified after Vector construction.) */
angle,
/** Vector options. Set to `undefined` to disable all options. */
options) {
this.angle = angle;
this.options = options;
this.magnitude = round(magnitude, { digits: options?.digits });
}
/** Splits the vector into its X and Y components. */
toComponents() {
const x = round(round(Math.cos(this.angle.radians), { digits: this.options?.digits }) * this.magnitude, {
digits: this.options?.digits,
});
const y = round(round(Math.sin(this.angle.radians), { digits: this.options?.digits }) * this.magnitude, {
digits: this.options?.digits,
});
return { x, y };
}
}