Skip to content

Instantly share code, notes, and snippets.

@zachelko
Created April 10, 2010 22:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zachelko/362346 to your computer and use it in GitHub Desktop.
Save zachelko/362346 to your computer and use it in GitHub Desktop.
General-purpose 2d vector class
// Vector2d.hpp
//
// Zach Elko
// 2010
//
// General-purpose 2d vector class
//
#ifndef VECTOR2D_H
#define VECTOR2D_H
#include <math.h>
#include <iostream>
// Internal 2d point
// Included here for brevity only
struct Point2d
{
float x;
float y;
void print()
{
std::cerr << "(" << x << "," << y << ")\n";
}
};
class Vector2d
{
public:
static Vector2d fromPoints(const Point2d& point1,
const Point2d& point2)
{
return Vector2d((point2.x - point1.x), (point2.y - point1.y));
}
static float distance(const Vector2d& vect1,
const Vector2d& vect2)
{
float xDiff = vect1.point.x - vect2.point.x;
float yDiff = vect1.point.y - vect2.point.y;
float dist = sqrt(pow(xDiff, 2) + pow(yDiff, 2));
return dist;
}
Vector2d(const float x, const float y)
{
point.x = x;
point.y = y;
}
Vector2d(const Point2d& point)
{
this->point.x = point.x;
this->point.y = point.y;
}
Vector2d()
{
point.x = point.y = 0;
}
int magnitude() const
{
return sqrt(pow(point.x, 2) + pow(point.y, 2));
}
void normalize()
{
int magnitude = this->magnitude();
point.x /= magnitude;
point.y /= magnitude;
}
void print() const
{
std::cerr << "(" << point.x << "," << point.y << ")\n";
}
Vector2d reverse() const
{
return Vector2d(-point.x, -point.y);
}
const Vector2d operator+(const Vector2d& vect) const
{
return Vector2d(point.x + vect.point.x, point.y + vect.point.y);
}
const Vector2d operator-(const Vector2d& vect) const
{
return Vector2d(point.x - vect.point.x, point.y - vect.point.y);
}
const Vector2d operator*(const float scalar) const
{
return Vector2d(this->point.x * scalar, this->point.y * scalar);
}
const Vector2d operator/(const float scalar) const
{
return Vector2d(this->point.x / scalar, this->point.y / scalar);
}
Point2d getPoint() const
{
return point;
}
void setPoint(const Point2d& point)
{
this->point = point;
}
private:
Point2d point;
};
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment