-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVector2.java
78 lines (58 loc) · 1.63 KB
/
Vector2.java
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import java.util.Arrays;
import java.util.concurrent.ThreadLocalRandom;
class Vector2 {
public double[] v = new double[2];
public double x() {
return v[0];
}
public double y() {
return v[1];
}
public void randomize(double min, double max) {
this.v[0] = ThreadLocalRandom.current().nextDouble(min, max);
this.v[1] = ThreadLocalRandom.current().nextDouble(min, max);
}
public void add(Vector2 vec) {
this.v[0] += vec.v[0];
this.v[1] += vec.v[1];
}
public void sub(Vector2 vec) {
this.v[0] -= vec.v[0];
this.v[1] -= vec.v[1];
}
public void multiply(Vector2 vec) {
this.v[0] *= vec.v[0];
this.v[1] *= vec.v[1];
}
public void divide(Vector2 vec) {
this.v[0] /= vec.v[0];
this.v[1] /= vec.v[1];
}
public double magnitude() {
return (double)Math.sqrt(Math.pow(this.x(), 2) + Math.pow(this.y(), 2));
}
public void normalize() {
double mag = magnitude();
if (mag == 0) return;
this.v[0] /= mag;
this.v[1] /= mag;
}
public void setMag(double magnitude) {
this.normalize();
this.v[0] *= magnitude;
this.v[1] *= magnitude;
}
public void limit(double max) {
// https://p5js.org/reference/#/p5.Vector/limit
// something like this?
double mag = magnitude();
if (mag > max) {
double scale = max / mag;
this.v[0] *= scale;
this.v[1] *= scale;
}
}
public void print() {
System.out.println(Arrays.toString(this.v));
}
}