Skip to content

Instantly share code, notes, and snippets.

@eduardonunesp

eduardonunesp/main.cpp

Last active May 15, 2020
Embed
What would you like to do?
Vector2 template with useful functions for geometry
#include <iostream>
#include "Vector2.h"
int main(int argc, const char * argv[]) {
Vector2<float> u {-8, 1};
Vector2<float> v {-2, 7};
std::cout << "Anglen (degrees): " << u.angle(v) * (180/M_PI) << std::endl;
return 0;
}
#ifndef VECTOR2_H
#define VECTOR2_H
#include <string>
#include <sstream>
#include <cmath>
template <typename T>
class Vector2
{
public:
T x;
T y;
// MARK: - Constructor
/// Default constructor
explicit Vector2<T>(): x(0), y(0) {}
/// Cosntructor with X and Y parameters
/// @param x X parameter of the vector
/// @param y Y parameter of the vector
Vector2<T>(T x, T y): x(x), y(y) {}
// MARK: - Vector math functions
/// Returns the magnitude of this vector
T magnitude() const
{
return std::sqrt(pow(x, 2) + pow(y, 2));
}
/// Normalizes the vector
void normalize() const
{
T l = magnitude();
if (l > 0) {
(*this) *= 1.0f / l;
}
}
/// Returns the dot product between two vectors
/// @param other the other vector
T dot(const Vector2 &other) const
{
return (x * other.x) + (y * other.y);
}
/// Returns the cross product between two vectors
/// @param other the other vector
T cross(const Vector2 &other)
{
return (x * other.y) + (y * other.x);
}
/// Returns the angle between two vectors in radians
/// Multiple for (180/M_PI) to return the angle in degrees
/// @param other the other vector
T angle(const Vector2 &other) const
{
auto mag = magnitude();
auto other_mag = other.magnitude();
auto dot_product = dot(other);
return std::acos(dot_product / (mag * other_mag));
}
// MARK: - Operators
Vector2 operator+(const Vector2 &other) const
{
return Vector2(x + other.x, y + other.y);
}
friend Vector2 &operator+=(Vector2 &other1, const Vector2 &other2)
{
other1.x += other2.x;
other1.y += other2.y;
return other1;
}
Vector2 operator-(const Vector2 &other) const
{
return Vector2(x - other.x, y - other.y);
}
friend Vector2 &operator-=(Vector2 &other1, const Vector2 &other2)
{
other1.x -= other2.x;
other1.y -= other2.y;
return other1;
}
Vector2 operator*(float scalar) const
{
return Vector2(x * scalar, y * scalar);
}
Vector2 &operator*=(float scalar) const
{
x *= scalar;
y *= scalar;
return *this;
}
Vector2 operator/(float scalar) const
{
return Vector2(x / scalar, y / scalar);
}
Vector2 &operator/=(float scalar) const
{
x /= scalar;
y /= scalar;
return *this;
}
operator std::string() const {
std::ostringstream ss;
ss << "(" << x << "," << y << ")";
return ss.str();
}
};
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.