-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVec2.pde
100 lines (79 loc) · 1.75 KB
/
Vec2.pde
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
//////////////////////
//Vector Library
//CSCI 5611 Vector 2 Library [Example]
//////////////////////
public class Vec2 {
public float x, y;
public Vec2(float x, float y){
this.x = x;
this.y = y;
}
public String toString(){
return "(" + x+ "," + y +")";
}
public float length(){
return sqrt(x*x+y*y);
}
public float lengthSqr(){
return x*x+y*y;
}
public Vec2 plus(Vec2 rhs){
return new Vec2(x+rhs.x, y+rhs.y);
}
public void add(Vec2 rhs){
x += rhs.x;
y += rhs.y;
}
public Vec2 minus(Vec2 rhs){
return new Vec2(x-rhs.x, y-rhs.y);
}
public void subtract(Vec2 rhs){
x -= rhs.x;
y -= rhs.y;
}
public Vec2 times(float rhs){
return new Vec2(x*rhs, y*rhs);
}
public void mul(float rhs){
x *= rhs;
y *= rhs;
}
public void clampToLength(float maxL){
float magnitude = sqrt(x*x + y*y);
if (magnitude > maxL){
x *= maxL/magnitude;
y *= maxL/magnitude;
}
}
public void setToLength(float newL){
float magnitude = sqrt(x*x + y*y);
x *= newL/magnitude;
y *= newL/magnitude;
}
public void normalize(){
float magnitude = sqrt(x*x + y*y);
x /= magnitude;
y /= magnitude;
}
public Vec2 normalized(){
float magnitude = sqrt(x*x + y*y);
return new Vec2(x/magnitude, y/magnitude);
}
public float distanceTo(Vec2 rhs){
float dx = rhs.x - x;
float dy = rhs.y - y;
return sqrt(dx*dx + dy*dy);
}
}
Vec2 interpolate(Vec2 a, Vec2 b, float t){
return a.plus((b.minus(a)).times(t));
}
float interpolate(float a, float b, float t){
return a + ((b-a)*t);
}
float dot(Vec2 a, Vec2 b){
return a.x*b.x + a.y*b.y;
}
Vec2 projAB(Vec2 a, Vec2 b){
return b.times(a.x*b.x + a.y*b.y);
}