-
Notifications
You must be signed in to change notification settings - Fork 1
/
CVector2.cpp
executable file
·146 lines (110 loc) · 2.77 KB
/
CVector2.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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
//
// Simple 2D vector class
//
#include "stdafx.h"
#include "math.h"
#include "CVector2.h"
#define PI 3.14159265f
#define RAD2DEG(x) ((x) * 180.0f / PI) // Convert radians to degrees
#define DEG2RAD(x) ((x) * PI / 180.0f) // Convert degrees to radians
CVector2::CVector2(float initial_x, float initial_y) : x(initial_x), y(initial_y)
{
}
CVector2 CVector2::operator+(const CVector2 &v1)
{
CVector2 v2(x + v1.x, y + v1.y);
return v2;
}
CVector2 &CVector2::operator+=(const CVector2 &v1)
{
x += v1.x;
y += v1.y;
return *this;
}
CVector2 CVector2::operator-(const CVector2 &v1)
{
CVector2 v2(x - v1.x, y - v1.y);
return v2;
}
CVector2 CVector2::operator-()
{
CVector2 v1(-x, -y);
return v1;
}
CVector2 CVector2::operator*(float scale)
{
CVector2 v1(x * scale, y * scale);
return v1;
}
CVector2 &CVector2::operator*=(float scale)
{
x *= scale;
y *= scale;
return *this;
}
float CVector2::GetLength()
{
return (float)sqrt(GetDotProduct(this, this));
}
//
// Returns the angle this vector is pointing at, between 0.0 and 359.9 degrees.
// 0.0 means pointing fully along the x axis.
//
float CVector2::GetAngle()
{
return RAD2DEG((float)atan2(x, y));
}
//
// Rotate this vector by angle_in_degrees. Positive values are counterclockwise,
// negative values are clockwise
//
void CVector2::Rotate(float angle_in_degrees)
{
float angle_in_radians = DEG2RAD(angle_in_degrees);
float cosine = (float)cos(angle_in_radians);
float sine = (float)sin(angle_in_radians);
float new_x = (x * cosine) - (y * sine);
float new_y = (x * sine) + (y * cosine);
x = new_x;
y = new_y;
}
//
// Make this vector have length new_length
//
void CVector2::Normalize(float new_length)
{
float current_length = GetLength();
if (fabs(current_length) > 0.0001f)
{
float scale = new_length / current_length;
x *= scale;
y *= scale;
}
else
{
x = new_length;
y = 0.0f;
}
}
//
// Returns the distance between two position vectors
//
float GetDistanceBetween(CVector2 *v1, CVector2 *v2)
{
CVector2 difference = *v1 - *v2;
return difference.GetLength();
}
//
// Returns the dot product of two vectors
//
float GetDotProduct(CVector2 *v1, CVector2 *v2)
{
return (v1->x * v2->x) + (v1->y * v2->y);
}
//
// Clamp current_value to be between min_value and max_value
//
float Clamp(float current_value, float min_value, float max_value)
{
return min(max(current_value, min_value), max_value);
}