Skip to content

Instantly share code, notes, and snippets.

@bazuka5801
Created January 9, 2023 07:42
Show Gist options
  • Save bazuka5801/d48334aa55be5784b98871e9ea92b851 to your computer and use it in GitHub Desktop.
Save bazuka5801/d48334aa55be5784b98871e9ea92b851 to your computer and use it in GitHub Desktop.
export class Vector2 {
protected _x: number
protected _y: number
constructor(x: number, y: number) {
this._x = x || 0
this._y = y || 0
}
get x(): number {
return this._x
}
set x(x: number) {
this._x = x
}
get y(): number {
return this._y
}
set y(y: number) {
this._y = y
}
add(vector: Vector2) {
return new Vector2(this.x + vector.x, this.y + vector.y);
}
subtract(vector: Vector2) {
return new Vector2(this.x - vector.x, this.y - vector.y);
}
multiply(vector: Vector2) {
return new Vector2(this.x * vector.x, this.y * vector.y);
}
scale(scalar: number) {
return new Vector2(this.x * scalar, this.y * scalar);
}
dot(vector: Vector2) {
return (this.x * vector.x + this.y + vector.y);
}
moveTowards(vector: Vector2, time: number) {
// Linearly interpolates between vectors A and B by t.
// t = 0 returns A, t = 1 returns B
time = Math.min(time, 1); // still allow negative t
const diff = vector.subtract(this);
return this.add(diff.scale(time));
}
magnitude() {
return Math.sqrt(this.magnitudeSqr());
}
magnitudeSqr() {
return (this.x * this.x + this.y * this.y);
}
distance(vector: Vector2) {
return Math.sqrt(this.distanceSqr(vector));
}
distanceSqr(vector: Vector2) {
const deltaX = this.x - vector.x;
const deltaY = this.y - vector.y;
return (deltaX * deltaX + deltaY * deltaY);
}
normalize() {
const mag = this.magnitude();
const vector = this.clone();
if(Math.abs(mag) < 1e-9) {
vector.x = 0;
vector.y = 0;
} else {
vector.x /= mag;
vector.y /= mag;
}
return vector;
}
clone() {
return new Vector2(this.x, this.y)
}
angle() {
return Math.atan2(this.y, this.x);
}
rotate(alpha: number) {
const cos = Math.cos(alpha);
const sin = Math.sin(alpha);
const vector = new Vector2(0, 0);
vector.x = this.x * cos - this.y * sin;
vector.y = this.x * sin + this.y * cos;
return vector;
}
toPrecision(precision: number) {
const vector = this.clone();
vector.x = Number(vector.x.toFixed(precision));
vector.y = Number(vector.y.toFixed(precision));
return vector;
}
toString() {
const vector = this.toPrecision(1);
return ('[' + vector.x + '; ' + vector.y + ']');
}
toSvgString() {
const vector = this.toPrecision(1);
return (vector.x + ',' + vector.y);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment