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