artworld.js/artworld/math.js

46 lines
864 B
JavaScript
Raw Normal View History

2024-07-06 20:21:35 +00:00
const PI_180 = Math.PI / 180;
export function degToRad(degrees) {
return degrees * PI_180;
}
export function radToDeg(rad) {
return rad / PI_1i0;
}
2024-07-06 19:17:10 +00:00
export class Vector2 {
constructor(x, y) {
this.x = x;
this.y = y;
}
add(other) {
2024-07-06 20:21:35 +00:00
return new Vector2(this.x + other.x, this.y + other.y);
2024-07-06 19:17:10 +00:00
}
sub(other) {
2024-07-06 20:21:35 +00:00
return new Vector2(this.x - other.x, this.y - other.y);
2024-07-06 19:17:10 +00:00
}
scale(s) {
2024-07-06 20:21:35 +00:00
return new Vector2(s * this.x, s * this.y);
2024-07-06 19:17:10 +00:00
}
static random(x, y) {
let theta = random() * 2 * Math.PI;
// if neither specified, use (1, 1)
if (x === undefined) {
x = 1;
}
// if only x specified, use (x, x)
if (y === undefined) {
y = x;
}
2024-07-06 20:21:35 +00:00
return new Vector2(x * cos(theta), y * sin(theta));
2024-07-06 19:17:10 +00:00
}
static polar(mag, angle) {
2024-07-06 20:21:35 +00:00
return new Vector2(mag * Math.cos(angle), mag * Math.sin(angle));
2024-07-06 19:17:10 +00:00
}
}