1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- /*
- * 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 <cmath>
- 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 float v)
- {
- this->x *= v;
- this->y *= v;
- };
- 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);
- };
- };
- #endif /* PHYSICENGINE_VEC2_H */
|