Files
zombie-game/resources/js/engine/Vector2D.js
T
2026-09-07 20:37:40 +02:00

67 lines
1.3 KiB
JavaScript

export class Vector2D {
constructor(x = 0, y = 0) {
this.x = x;
this.y = y;
}
mulS(scalar) {
return new Vector2D(this.x * scalar, this.y * scalar);
}
mulV(vector) {
return new Vector2D(this.x * vector.x, this.y * vector.y);
}
divS(scalar) {
return new Vector2D(this.x / scalar, this.y / scalar);
}
divV(vector) {
return new Vector2D(this.x / vector.x, this.y / vector.y);
}
addS(scalar) {
return new Vector2D(this.x + scalar, this.y + scalar);
}
addV(vector) {
return new Vector2D(this.x + vector.x, this.y + vector.y);
}
subS(scalar) {
return new Vector2D(this.x - scalar, this.y - scalar);
}
subV(vector) {
return new Vector2D(this.x - vector.x, this.y - vector.y);
}
dot(vector) {
return this.x * vector.x + this.y * vector.y;
}
abs() {
return new Vector2D(Math.abs(this.x), Math.abs(this.y));
}
length() {
return Math.sqrt(this.dot(this));
}
lengthSqrt() {
return this.dot(this);
}
normalize() {
const length = this.length();
this.x /= length;
this.y /= length;
return this;
}
rotate(angle) {
const cos = Math.cos(angle);
const sin = Math.sin(angle);
return new Vector2D(this.x * cos - this.y * sin, this.x * sin + this.y * cos);
}
}