advent22/ui/src/components/rects/rectangles.ts

72 lines
1.5 KiB
TypeScript
Raw Normal View History

2023-01-17 00:51:52 +00:00
export class Vector2D {
2023-01-23 14:38:49 +00:00
public readonly x: number;
public readonly y: number;
2023-01-17 00:51:52 +00:00
constructor(x = 0, y = 0) {
2023-01-23 14:38:49 +00:00
this.x = x;
this.y = y;
2023-01-17 00:51:52 +00:00
}
public plus(other: Vector2D): Vector2D {
2023-01-23 14:38:49 +00:00
return new Vector2D(this.x + other.x, this.y + other.y);
2023-01-17 00:51:52 +00:00
}
public minus(other: Vector2D): Vector2D {
2023-01-23 14:38:49 +00:00
return new Vector2D(this.x - other.x, this.y - other.y);
2023-01-17 00:51:52 +00:00
}
}
export class Rectangle {
2023-01-23 14:38:49 +00:00
private readonly corner_1: Vector2D;
private readonly corner_2: Vector2D;
2023-01-17 00:51:52 +00:00
constructor(corner_1: Vector2D, corner_2: Vector2D) {
2023-01-23 14:38:49 +00:00
this.corner_1 = corner_1;
this.corner_2 = corner_2;
2023-01-17 00:51:52 +00:00
}
public get origin(): Vector2D {
2023-01-23 14:38:49 +00:00
return new Vector2D(
Math.min(this.corner_1.x, this.corner_2.x),
Math.min(this.corner_1.y, this.corner_2.y),
)
2023-01-17 00:51:52 +00:00
}
public get left(): number {
return this.origin.x;
}
public get top(): number {
return this.origin.y;
}
2023-01-17 23:34:42 +00:00
public get corner(): Vector2D {
2023-01-23 14:38:49 +00:00
return new Vector2D(
Math.max(this.corner_1.x, this.corner_2.x),
Math.max(this.corner_1.y, this.corner_2.y),
)
2023-01-17 23:34:42 +00:00
}
2023-01-17 00:51:52 +00:00
public get size(): Vector2D {
2023-01-23 14:38:49 +00:00
return this.corner.minus(this.origin);
2023-01-17 00:51:52 +00:00
}
public get width(): number {
return this.size.x;
}
public get height(): number {
return this.size.y;
}
2023-01-17 14:26:39 +00:00
public get area(): number {
return this.width * this.height;
}
2023-01-17 23:50:25 +00:00
public contains(point: Vector2D): boolean {
2023-01-23 14:38:49 +00:00
return point.x >= this.origin.x &&
point.y >= this.origin.y &&
point.x <= this.corner.x &&
point.y <= this.corner.y
2023-01-17 00:51:52 +00:00
}
}