Skip to content

Commit

Permalink
feat(core): improve Vector2 class (#985)
Browse files Browse the repository at this point in the history
  • Loading branch information
aarthificial committed Mar 11, 2024
1 parent 6b2dab3 commit 11ef7ea
Showing 1 changed file with 35 additions and 1 deletion.
36 changes: 35 additions & 1 deletion packages/core/src/types/Vector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,14 @@ export class Vector2 implements Type, WebGLConvertible {
return new Vector2(Math.floor(this.x), Math.floor(this.y));
}

public get rounded(): Vector2 {
return new Vector2(Math.round(this.x), Math.round(this.y));
}

public get ceiled(): Vector2 {
return new Vector2(Math.ceil(this.x), Math.ceil(this.y));
}

public get perpendicular(): Vector2 {
return new Vector2(this.y, -this.x);
}
Expand All @@ -346,6 +354,7 @@ export class Vector2 implements Type, WebGLConvertible {
public get ctg(): number {
return this.x / this.y;
}

public constructor();
public constructor(from: PossibleVector2);
public constructor(x: number, y: number);
Expand Down Expand Up @@ -447,7 +456,7 @@ export class Vector2 implements Type, WebGLConvertible {
}

/**
* Rotates the vector around a point by the provided angle.
* Rotate the vector around a point by the provided angle.
*
* @param angle - The angle by which to rotate in degrees.
* @param center - The center of rotation. Defaults to the origin.
Expand All @@ -473,6 +482,22 @@ export class Vector2 implements Type, WebGLConvertible {
return new Vector2(this.x, this.y + value);
}

/**
* Transform the components of the vector.
*
* @example
* Raise the components to the power of 2.
* ```ts
* const vector = new Vector2(2, 3);
* const result = vector.transform(value => value ** 2);
* ```
*
* @param callback - A callback to apply to each component.
*/
public map(callback: (value: number, index: number) => number) {
return new Vector2(callback(this.x, 0), callback(this.y, 1));
}

public toSymbol(): symbol {
return Vector2.symbol;
}
Expand All @@ -481,6 +506,10 @@ export class Vector2 implements Type, WebGLConvertible {
return `Vector2(${this.x}, ${this.y})`;
}

public toArray() {
return [this.x, this.y];
}

public toUniform(
gl: WebGL2RenderingContext,
location: WebGLUniformLocation,
Expand Down Expand Up @@ -522,4 +551,9 @@ export class Vector2 implements Type, WebGLConvertible {
Math.abs(this.y - other.y) <= threshold + Number.EPSILON
);
}

public *[Symbol.iterator]() {
yield this.x;
yield this.y;
}
}

0 comments on commit 11ef7ea

Please sign in to comment.