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

105 lines
2.2 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
}
2023-01-24 23:11:01 +00:00
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
}
2023-01-24 23:11:01 +00:00
public scale(other: number): Vector2D {
return new Vector2D(this.x * other, this.y * other);
}
public equals(other: Vector2D): boolean {
return 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 = new Vector2D(), corner_2 = new Vector2D()) {
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;
}
public get middle(): Vector2D {
return this.origin.plus(this.size.scale(0.5))
}
2023-01-17 14:26:39 +00:00
public get area(): number {
return this.width * this.height;
}
public equals(other: Rectangle): boolean {
return this.origin.equals(other.origin) &&
this.corner.equals(other.corner);
}
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 &&
2023-01-31 14:21:06 +00:00
point.y <= this.corner.y;
}
public update(corner_1?: Vector2D, corner_2?: Vector2D): Rectangle {
return new Rectangle(
corner_1 || this.corner_1,
corner_2 || this.corner_2,
);
}
public move(vector: Vector2D): Rectangle {
return new Rectangle(
this.corner_1.plus(vector),
this.corner_2.plus(vector),
);
2023-01-17 00:51:52 +00:00
}
}