4d4b85add9546abc4aabd8fb3f6a11bba420ed82
[physics.git] / src / Vector2.cpp
1 #include "Vector2.h"
2 #include "mathw.h"
3
4 /// ***** Constructors/Destructors *****
5
6 Vector2::Vector2()
7   : x(0), y(0)
8 {
9
10 }
11 Vector2::Vector2(float x, float y)
12   : x(x), y(y)
13 {
14
15 }
16 Vector2::Vector2(const Vector2& vec)
17   : x(vec.x), y(vec.y)
18 {
19
20 }
21 Vector2::~Vector2()
22 {
23
24 }
25
26 /// ***** Public Class Methods *****
27
28 void Vector2::zero()
29 {
30     x = 0;
31     y = 0;
32 }
33 void Vector2::unit()
34 {
35     float len = length();
36
37     x /= len;
38     y /= len;
39 }
40
41 float Vector2::angle() const
42 {
43     //TODO
44     //return atan2A(y,x);
45     return 0;
46 }
47 float Vector2::length() const
48 {
49     return sqrt(x*x + y*y);
50 }
51
52
53 string Vector2::toString() const
54 {
55      // long just to be safe
56     char* strX = new char[50];
57     char* strY = new char[50];
58
59     sprintf(strX, "%f", x);
60     sprintf(strY, "%f", y);
61
62     string val = (string)"Vector2  x: " + strX + ", y: " + strY;
63
64      // deletes the allocated memory, not just what is used by sprintf
65     delete []strX;
66     delete []strY;
67
68     return val;
69 }
70 void Vector2::print() const
71 {
72     printf("%s\n",toString().c_str());
73 }
74
75
76 Vector2 Vector2::add(const Vector2& vec) const
77 {
78     return Vector2(x+vec.x, y+vec.y);
79 }
80 Vector2 Vector2::subtract(const Vector2& vec) const
81 {
82     return Vector2(x-vec.x, y-vec.y);
83 }
84 Vector2 Vector2::multiply(float c) const
85 {
86     return Vector2(x*c, y*c);
87 }
88 Vector2 Vector2::divide(float c) const
89 {
90     return Vector2(x/c, y/c);
91 }
92
93 /// ***** Public Methods *****
94
95 Vector2 operator+(const Vector2& vec1, const Vector2& vec2)
96 {
97     return vec1.add(vec2);
98 }
99 Vector2 operator-(const Vector2& vec1, const Vector2& vec2)
100 {
101     return vec1.subtract(vec2);
102 }
103 Vector2 operator*(float c, const Vector2& vec)
104 {
105     return vec.multiply(c);
106 }
107 Vector2 operator*(const Vector2& vec, float c)
108 {
109     return vec.multiply(c);
110 }
111 Vector2 operator/(const Vector2& vec, float c)
112 {
113     return vec.divide(c);
114 }
115
116
117 void operator+=(Vector2& vec1, const Vector2& vec2)
118 {
119     vec1.x += vec2.x;
120     vec1.y += vec2.y;
121 }
122 void operator-=(Vector2& vec1, const Vector2& vec2)
123 {
124     vec1.x -= vec2.x;
125     vec1.y -= vec2.y;
126 }
127 void operator*=(Vector2& vec, float c)
128 {
129     vec.x *= c;
130     vec.y *= c;
131 }
132 void operator/=(Vector2& vec, float c)
133 {
134     vec.x /= c;
135     vec.y /= c;
136 }