// // vector2d.h // // A vector in 2d space // // Copyright (C) J. Belson 2000.12.16 // #include #include "vector2d.h" using namespace std; /** * Constructor */ vector2d::vector2d(float i, float j) { this->i = i; this->j = j; } /// /// Calculate A.B /// Divide result by |A| and |B| to get cos(angle) /// float vector2d::dot_product(vector2d &v) { return i*v.i + j*v.j; } #if 0 vector2d vector2d::vector_product(vector2d &v) { vector3d tmp( j*v.k - k*v.j, k*v.i - i*v.k, i*v.j - j*v.i); return tmp; } #endif /// Calculate magnitude of this vector float vector2d::magnitude(void) { return sqrt(i*i + j*j); } /// /// Normalise by dividing each component /// by vector magnitude /// void vector2d::normalise(void) { float mag = magnitude(); if (mag) { i /= mag; j /= mag; } } /// /// Rotate this vector clockwise /// Should be doing this with matrices but hey. /// void vector2d::rotate(float radians) { float new_i = i*cos(radians) + j*sin(radians); float new_j = -i*sin(radians) + j*cos(radians); i = new_i; j = new_j; } // // Operators // /// Add another vector to this one vector2d vector2d::operator+(vector2d v) { vector2d temp(v.i + i, v.j + j); return temp; } /// Scale this vector by a constant vector2d vector2d::operator*(float f) { vector2d temp(i * f, j * f); return temp; } /// Write vector attributes to a stream /// @param str stream to write to /// @param v vector to operate on ostream& operator<<(ostream& str, vector2d& v) { str << "[" << v.i << ", " << v.j << "]"; return str; }