-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathVector2D.hpp
93 lines (75 loc) · 2.57 KB
/
Vector2D.hpp
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
#pragma once
#include <cmath>
#include <stdexcept>
struct Vector2D {
float x, y;
Vector2D() : x(0), y(0) {}
Vector2D(float x_val, float y_val) : x(x_val), y(y_val) {}
float operator[](int i) const;
float& operator[](int i);
Vector2D Subtract(const Vector2D& other) const {
return Vector2D(x - other.x, y - other.y);
}
Vector2D Add(const Vector2D& other) const {
return Vector2D(x + other.x, y + other.y);
}
Vector2D Divide(const Vector2D& other) const {
return Vector2D(x / other.x, y / other.y);
}
Vector2D Divide(float scalar) const {
return Vector2D(x / scalar, y / scalar);
}
float DotProduct(const Vector2D& other) const {
return x * other.x + y * other.y;
}
float Magnitude() const {
return std::sqrt(x * x + y * y);
}
float Distance(const Vector2D& other) const {
Vector2D diff = Subtract(other);
return diff.Magnitude();
}
Vector2D Multiply(float scalar) const {
return Vector2D(x * scalar, y * scalar);
}
Vector2D Normalized() const {
Vector2D result;
float length = std::sqrt(x * x + y * y);
if (length != 0) {
result.x = x / length;
result.y = y / length;
}
return result;
}
Vector2D MultipliedByScalar(float scalar) const {
Vector2D result;
result.x = x * scalar;
result.y = y * scalar;
return result;
}
Vector2D Clamp() const {
//pitch doesnt have a full rotation so just set it to max value if its more than that
float clampedX = x;
if (clampedX < -89) clampedX = -89;
if (clampedX > 89) clampedX = 89;
//yaw has a full rotation so we might want to move it to the oposite side from negative to positive or vice versa
float clampedY = y;
if (clampedY < -180) clampedY += 360;
if (clampedY > 180) clampedY -= 360;
//create the vector
if (clampedX > 89 || clampedX < -89) throw std::invalid_argument("SHIT CLAMPING OF PITCH. CHECK YOUR CODE");
if (clampedY > 180 || clampedY < -180) throw std::invalid_argument("SHIT CLAMPING OF YAW. CHECK YOUR CODE");
return Vector2D(clampedX, clampedY);
}
bool IsZeroVector() {
return x == 0 && y == 0;
}
bool operator==(const Vector2D& other) const {
float epsilon = 1e-5;
return (std::abs(x - other.x) < epsilon)
&& (std::abs(y - other.y) < epsilon);
}
bool operator!=(const Vector2D& other) const {
return !(*this == other);
}
};