Created
May 12, 2011 19:56
-
-
Save migimunz/969315 to your computer and use it in GitHub Desktop.
A vector2D class with overloaded operators to make it easy to work with. All methods (except assignment operator, obviously) are const.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef VECTORND_H | |
#define VECTORND_H | |
namespace vector | |
{ | |
template <typename T> | |
struct vector2D | |
{ | |
T x, y; | |
vector2D() : x(0), y(0) | |
{ | |
} | |
vector2D(T x, T y) | |
{ | |
this->x = x; | |
this->y = y; | |
} | |
vector2D(const vector2D<T> &v) | |
{ | |
this->x = v.x; | |
this->y = v.y; | |
} | |
vector2D &operator=(const vector2D<T> &v) | |
{ | |
this->x = v.x; | |
this->y = v.y; | |
return *this; | |
} | |
T& operator[](int i) const | |
{ | |
return i == 0 ? x : y; | |
} | |
T& operator()(int i) const | |
{ | |
return (*this)[i]; | |
} | |
vector2D<T> operator()() const | |
{ | |
return normalize(); | |
} | |
bool operator==(const vector2D<T> &v) const | |
{ | |
return x == v.x && y == v.y; | |
} | |
bool operator!=(const vector2D<T> &v) const | |
{ | |
return !(*this == v); | |
} | |
vector2D operator+(const vector2D<T> &v) const | |
{ | |
return vector2D<T>(x+v.x, y+v.y); | |
} | |
vector2D operator-(const vector2D<T> &v) const | |
{ | |
return vector2D<T>(x-v.x, y-v.y); | |
} | |
//scaling | |
vector2D operator*(T v) const | |
{ | |
return vector2D<T>(x*v, y*v); | |
} | |
//scaling | |
vector2D operator/(T v) const | |
{ | |
return vector2D<T>(x/v, y/v); | |
} | |
//component-wise scaling | |
vector2D operator*(const vector2D<T> &v) const | |
{ | |
return vector2D<T>(x*v.x, y*v.y); | |
} | |
//component-wise scaling | |
vector2D operator/(const vector2D<T> &v) const | |
{ | |
return vector2D<T>(x/v.x, y/v.y); | |
} | |
vector2D operator-() const | |
{ | |
return (Vector2D(-x, -y)); | |
} | |
vector2D operator+() const | |
{ | |
return *this; | |
} | |
T length2() const | |
{ | |
return x*x + y*y; | |
} | |
T length() const | |
{ | |
return (T)sqrt(length2()); | |
} | |
vector2D normalize() const | |
{ | |
return *this * (1/length()); | |
} | |
vector2D cw() const | |
{ | |
return vector2D(-y, +x); | |
} | |
vector2D ccw() const | |
{ | |
return vector2D(+y, -x); | |
} | |
vector2D rotate(T angle) const | |
{ | |
T s = sin(angle), c = cos(angle); | |
return vector2D(x * c - y * s, y * c + x * s); | |
} | |
static T dot(const vector2D<T> &a, const vector2D<T> &b) | |
{ | |
return a.x*b.x + a.y*b.y; | |
} | |
}; | |
} | |
typedef vector2D<int> vector2Di; | |
typedef vector2D<float> vector2Df; | |
typedef vector2D<double> vector2Dd; | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment