Phyzix
Loading...
Searching...
No Matches
Vector.h
1//
2// Created by shams on 9/10/24.
3//
4
5#ifndef PHYZIX_VECTOR_H
6#define PHYZIX_VECTOR_H
7
8
9#include "app/math/Math.h"
10#include "app/lib/printf.h"
11
12class Vector {
13public:
14 float x; // can be a_x, v_x, x, i, ..
15 float y; // can be a_y, v_y, y, j, ..
16
17 Vector(float x, float y): x(x), y(y) {}
18
19 Vector operator+(Vector other) const {
20 return {this->x + other.x, this->y + other.y};
21 }
22
23 Vector operator*(float scalar) const {
24 return {this->x * scalar, this->y * scalar};
25 }
26
27 float operator*(Vector other) const {
28 // dot product
29 return this->x * other.x + this->y * other.y;
30 }
31
32 float getMagnitude() const {
33 return Math::sqrt(Math::pow(this->x, 2) + Math::pow(this->y, 2));
34 }
35
36 float getDirection() const {
37 if (Math::sign(y) == 1) {
38 if (Math::sign(x) == 1) {
39 // First Quad
40 return Math::atan(y, x);
41 } else {
42 // Second Quad
43 return Math::PI - Math::atan(y, x);
44 }
45 } else {
46 if (Math::sign(x) == 1) {
47 // Fourth Quad
48 return Math::PI + Math::PI - Math::atan(y, x);
49 } else {
50 // Third Quad
51 return Math::PI + Math::atan(y, x);
52 }
53 }
54 }
55
56 Vector getNormal() const {
57 float magnitude = getMagnitude();
58 return {this->x / magnitude, this->y / magnitude};
59 }
60
61 Vector getPerpendicular() const {
62 return {-this->y, this->x};
63 }
64
65 Vector getResolvedAround(Vector normal) const {
66 float magnitude = getMagnitude();
67 float angle = this->getDirection() - normal.getDirection();
68 return { -magnitude * Math::sin(angle), magnitude * Math::cos(angle) };
69 }
70
71 Vector getUnResolvedFrom(Vector normal) const {
72 float magnitude = getMagnitude();
73 float angle = normal.getDirection();
74 return { magnitude * Math::cos(angle), magnitude * Math::sin(angle) };
75 }
76
77 void print(bool verbose = true) const {
78 if (verbose)
79 printf("Vector x: %f, y: %f (%f, %f)\n", x, y, getMagnitude(), getDirection() * 180 / Math::PI);
80 else
81 printf("%f |_ %f\n", getMagnitude(), getDirection() * 180 / Math::PI);
82 }
83};
84
85
86#endif //PHYZIX_VECTOR_H
static float atan(float m)
get the arc tangent of a ratio if slope approaches infinity
Definition Math.h:157
static float pow(float base, int exponent)
exponentiation
Definition Math.h:23
static int sign(float x)
get the sign of number
Definition Math.h:138
static float sqrt(float n)
get the square root of the number
Definition Math.h:99
static constexpr float PI
Definition Math.h:15
static float cos(float angle)
get the cosine of the angle
Definition Math.h:119
static float sin(float angle)
get the sine of the angle
Definition Math.h:147
Definition Vector.h:12