-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVec2.cpp
129 lines (104 loc) · 2.18 KB
/
Vec2.cpp
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include "Vec2.h"
#include "Tool.h"
#include <cmath>
/*
角度的转单位向量
*/
Vec2::Vec2(double angle) {
x = -cos(angle / 180.0 * M_PI);
y = sin(angle / 180.0 * M_PI);
}
double Vec2::normSquare() const {
return x * x + y * y;
}
double Vec2::norm() const {
return sqrt(normSquare());
}
Vec2 Vec2::normalize() const {
double n = norm();
Vec2 v(x, y);
return v / n;
}
Vec2 Vec2::project(const Vec2& v) const {
double normNsquare = v.normSquare();
Vec2 u(x, y);
Vec2 prjnV = v.normalize() * norm();
return prjnV;
}
Vec2 Vec2::perpendicular() const {
Vec2 v(y, -x);
return v;
}
double Vec2::angleWith(Vec2& n) {
Vec2 v(x, y);
return acos(v * n / v.norm() / n.norm()) / 3.14156535 * 180.0;
}
double Vec2::toAngle() {
Vec2 right = Vec2(1, 0);
return angleWith(right);
}
//Vec2 &Vec2::operator = (const Vec2& v){
// if (this != &v) {
// x = v.x;
// y = v.y;
// }
// return *this;
//}
bool Vec2::operator == (const Vec2& v)const {
return (x == v.x) && (y == v.y);
}
bool Vec2::operator != (const Vec2& v)const {
return (x != v.x) || (y != v.y);
}
bool Vec2::operator < (const Vec2& v) const {
if (x != v.x) return x < v.x;
return y < v.y;
}
Vec2 Vec2::operator + (const Vec2& v)const {
Vec2 ans(x + v.x, y + v.y);
return ans;
}
Vec2 Vec2::operator - (const Vec2& v) const {
Vec2 ans(x - v.x, y - v.y);
return ans;
}
Vec2 Vec2::operator - () const {
Vec2 ans(-x, -y);
return ans;
}
double Vec2::operator * (const Vec2& v)const {
return x * v.x + y * v.y;
}
Vec2 Vec2::operator * (double k) const {
Vec2 ans(x * k, y * k);
return ans;
}
double Vec2::cross(const Vec2& v) const {
return (x * v.y - v.x * y);
}
Vec2 Vec2::operator / (double k)const {
if (k <= 1e-6) return *this;
Vec2 ans(x / k, y / k);
return ans;
}
Vec2 Vec2::moveToword(Vec2 ed, double dtSpeedx, double dtSpeedy) {
Vec2 st(x, y);
Vec2 s = (ed - st).normalize();
Vec2 ss(s.x * dtSpeedx, s.y * dtSpeedy);
Vec2 p = st + ss;
Vec2 t = (ed - p).normalize();
if (s == -t) { //超了
p = ed;
}
return p;
}
Vec2 Vec2::moveToword(Vec2 ed, double dtSpeed) {
Vec2 st(x, y);
Vec2 s = (ed - st).normalize();
Vec2 p = st + s * dtSpeed;
Vec2 t = (ed - p).normalize();
if (s == -t) { //超了
p = ed;
}
return p;
}