-
Notifications
You must be signed in to change notification settings - Fork 9
/
Vector2D.cpp
78 lines (64 loc) · 1.56 KB
/
Vector2D.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
#include "Vector2D.h"
#include <math.h>
//function to calculate the length of a vector
float Vector2D::length()
{
return (float)sqrt((m_x * m_x) + (m_y * m_y));
}
//addition of two vectors using + operator
Vector2D Vector2D::operator + (const Vector2D& v2) const
{
return Vector2D(m_x + v2.m_x, m_y + v2.m_y);
}
//addition of two vectors using += operator
Vector2D& operator += (Vector2D& v1, const Vector2D& v2)
{
v1.m_x += v2.m_x;
v1.m_y += v2.m_y;
return v1;
}
//multiplication of a vector with a scalar number using * operator
Vector2D Vector2D::operator * (float scalar)
{
return Vector2D(m_x * scalar, m_y * scalar);
}
//multiplication of a vector with a scalar number using *= operator
Vector2D& Vector2D::operator *= (float scalar)
{
m_x *= scalar;
m_y *= scalar;
return *this;
}
//subtraction of two vectors using - operator
Vector2D Vector2D::operator - (const Vector2D& v2) const
{
return Vector2D(m_x - v2.m_x, m_y - v2.m_y);
}
//subtraction of two vectors using -= operator
Vector2D& operator -= (Vector2D& v1, const Vector2D& v2)
{
v1.m_x -= v2.m_x;
v1.m_y -= v2.m_y;
return v1;
}
//division of a vector by a scalar number using / operator
Vector2D Vector2D::operator / (float scalar)
{
return Vector2D(m_x / scalar, m_y / scalar);
}
//division of a vector by a scalar number using /= operator
Vector2D& Vector2D::operator /= (float scalar)
{
m_x /= scalar;
m_y /= scalar;
return *this;
}
//function to normalize a vector
void Vector2D::normalize()
{
float l = length();
if (l > 0) //we never want to attempt to divide by 0
{
(*this) *= 1 / l;
}
}