Skip to content

Instantly share code, notes, and snippets.

@sidthesloth92
Last active December 23, 2020 14:28
Show Gist options
  • Save sidthesloth92/d41aab5c846f7319716b89f60a98ea2b to your computer and use it in GitHub Desktop.
Save sidthesloth92/d41aab5c846f7319716b89f60a98ea2b to your computer and use it in GitHub Desktop.
A simple lightweight math vector implementation.
/**
* Represents a math vector with x, y position, direction and magnitude.
*/
class Vector {
constructor(x, y) {
this._compute(x, y);
}
_compute(x, y) {
this.x = x;
this.y = y;
this.angle = Math.atan2(y, x);
this.length = Math.sqrt(x * x + y * y);
}
/**
* Sets the angle of the vector with respect to the unit vector.
* @param angle The angle to unity.
*/
setAngle(angle) {
this.angle = angle;
this.x = Math.cos(this.angle) * this.length;
this.y = Math.sin(this.angle) * this.length;
}
/**
* Sets the distance to unit vector.
* @param length The length to the unit vector.
*/
setLength(length) {
this.length = length;
this.x = Math.cos(this.angle) * this.length;
this.y = Math.sin(this.angle) * this.length;
}
/**
* Add the given vector to the current vector.
* @param v The vector to add.
*/
add(v) {
this._compute(this.x + v.x, this.y + v.y);
}
/**
* Subtracts the given vector to the current vector.
* @param v The vector to subtract.
*/
subtract(v) {
this._compute(this.x - v.x, this.y - v.y);
}
/**
* Multiplies the current vector by a scalar.
* @param scalar The scalar to multiply.
*/
multiply(scalar) {
this._compute(this.x * scalar, this.y * scalar);
}
/**
* Divides the current vector by a scalar.
* @param scalar The scalar to divide.
*/
divide(scalar) {
this._compute(this.x / scalar, this.y / scalar);
}
/**
* Adds two vectors together.
* @param v1 Vector operand one for addition.
* @param v2 Vector operand two for addition.
*/
static add(v1, v2) {
const x = v1.x + v2.x;
const y = v1.y + v2.y;
return new Vector(x, y);
}
/**
* Subtract two vectors.
* @param v1 Vector operand one for subtraction.
* @param v2 Vector operand two for subtraction.
*/
static subtract(v1, v2) {
const x = v1.x - v2.x;
const y = v1.y - v2.y;
return new Vector(x, y);
}
/**
* Multiplies a vector and a scalar.
* @param v1 Vector operand for multiplication.
* @param v2 Scalar operand for multiplication.
*/
static multiply(v, k) {
return new Vector(v.x * k, v.y * k);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment