summaryrefslogtreecommitdiff
path: root/2026/games/ellg/vector.js
blob: cf32d818d8c5f9dead85351fc172073b05d70fcd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
export class Vector {
  static of([x, y]) {
    return new Vector(x, y)
  }

  constructor(x, y) {
    this.x = x
    this.y = y
  }

  add(val) {
    return new Vector(this.x + val.x, this.y + val.y)
  }

  subtract(val) {
    return new Vector(this.x - val.x, this.y - val.y)
  }

  multiply(scalar) {
    return new Vector(this.x * scalar, this.y * scalar)
  }

  divide(scalar) {
    return new Vector(this.x / scalar, this.y / scalar)
  }

  dot(other) {
    return this.x * other.x + this.y * other.y
  }

  cross(other) {
    return this.x * other.y - other.x * this.y
  }

  hadamard(other) {
    return new Vector(this.x * other.x, this.y * other.y)
  }

  length() {
    return Math.sqrt(this.x ** 2 + this.y ** 2)
  }

  distance(other) {
    return this.subtract(other).length()
  }

  normalize() {
    const length = this.length()
    if (length === 0) {
      return new Vector(0, 0)
    }
    return new Vector(this.x / length, this.y / length)
  }

  rotateByRadians(radians) {
    const cos = Math.cos(radians)
    const sin = Math.sin(radians)
    return new Vector(this.x * cos - this.y * sin, this.x * sin + this.y * cos)
  }

  rotateByDegrees(degrees) {
    return this.rotateByRadians((degrees * Math.PI) / 180)
  }
}