/* * 2D Physic Engine * vec2.h: Definition and implementation of the 2D vector * Based on pikuma.com Learn Game Physics Engine Programming course. * Copyright (c) 2022 986-Studio. All Right Reserved * * Created by Manoƫl Trapier on 07/06/2022. */ #ifndef PHYSICENGINE_VEC2_H #define PHYSICENGINE_VEC2_H #include struct vec2 { double x, y; vec2() : x(0.0), y(0.0) {}; vec2(double x, double y) : x(x), y(y) {}; ~vec2() = default; void add(const vec2 &v) { this->x += v.x; this->y += v.y; }; void sub(const vec2 &v) { this->x -= v.x; this->y -= v.y; }; void scale(const double n) { this->x *= n; this->y *= n; }; vec2 rotate(const double angle) const { vec2 result(x * cos(angle) - y * sin(angle), x * sin(angle) + y * cos(angle)); return result; }; double magnitude() const { return sqrt(this->x * this->x + this->y * this->y); }; double magnitudeSquared() const { return this->x * this->x + this->y * this->y; }; vec2 &normalise() { double m = this->magnitude(); if (m != 0.0) { this->x /= m; this->y /= m; } return *this; }; vec2 unitVector() const { double m = this->magnitude(); vec2 ret; if (m != 0.0) { ret.x = this->x / m; ret.y = this->y / m; } return ret; }; vec2 normal() const { vec2 ret(this->y, -this->x); return ret.normalise(); }; double dot(const vec2 &v) const { return (this->x * v.x) + (this->y + v.y); }; double cross(const vec2 &v) const { /* return the imaginary Z component */ return (this->x * v.y) - (this->y * v.x); }; vec2 & operator = (const vec2 &v) { this->x = v.x; this->y = v.y; return *this; }; bool operator == (const vec2 &v) const { return (this->x == v.x) && (this->y == v.y); }; bool operator != (const vec2 &v) const { return (this->x != v.x) || (this->y != v.y); }; vec2 operator + (const vec2 &v) const { return vec2(this->x + v.x, this->y + v.y); } vec2 operator - (const vec2 &v) const { return vec2(this->x - v.x, this->y - v.y); }; vec2 operator * (const double n) const { return vec2(this->x * n, this->y * n); }; vec2 operator / (const double n) const { return vec2(this->x / n, this->y / n); }; vec2 operator - () { return vec2(-this->x, -this->y); }; vec2 & operator += (const vec2 &v) { this->x += v.x; this->y += v.y; return *this; }; vec2 & operator -= (const vec2 &v) { this->x -= v.x; this->y -= v.y; return *this; } vec2 & operator *= (const double n) { this->x *= n; this->y *= n; return *this; } vec2 & operator /= (const double n) { this->x /= n; this->y /= n; return *this; } }; #endif /* PHYSICENGINE_VEC2_H */