Shmup/src/utilities/vector2D.cpp

111 lines
2.2 KiB
C++

#include "vector2D.h"
#include "fast_trig.h"
Vector2D::Vector2D() {
this->x = libnum::num32(0);
this->y = libnum::num32(0);
}
Vector2D::Vector2D(float x, float y) {
this->x = libnum::num32(x);
this->y = libnum::num32(y);
}
Vector2D::Vector2D(libnum::num32 x, libnum::num32 y) {
this->x = x;
this->y = y;
}
Vector2D::Vector2D(const Vector2D &v) {
this->x = v.x;
this->y = v.y;
}
Vector2D::~Vector2D() {}
void Vector2D::Set(Vector2D v) {
this->x = v.x;
this->y = v.y;
}
void Vector2D::Normalise(void) {
libnum::num32 len = this->Length();
this->x /= len;
this->y /= len;
}
Vector2D Vector2D::Clone(void) {
Vector2D NewVector(this->x, this->y);
return NewVector;
}
Vector2D Vector2D::MakeVector(Vector2D A, Vector2D B) {
Vector2D NewVector(B.x - A.x, B.y - A.y);
return NewVector;
}
void Vector2D::AddVectors(Vector2D a, Vector2D b) {
this->x = a.x + b.x;
this->y = a.y + b.y;
}
void Vector2D::Add(Vector2D v, libnum::num32 scale) {
this->x += v.x * scale;
this->y += v.y * scale;
}
void Vector2D::SubtractVectors(Vector2D a, Vector2D b) {
this->x = a.x - b.x;
this->y = a.y - b.y;
}
void Vector2D::Subtract(Vector2D v, libnum::num32 scale) {
this->x -= v.x * scale;
this->y -= v.y * scale;
}
libnum::num32 Vector2D::Length(void) {
return sqrt_num32(this->x * this->x + this->y * this->y);
}
void Vector2D::Scale(libnum::num32 scale) {
this->x *= scale;
this->y *= scale;
}
libnum::num32 Vector2D::Dot(Vector2D v) { return (this->x * v.x + this->y * v.y); }
libnum::num32 Vector2D::Det(Vector2D v) { return (this->x * v.y - this->y * v.x); }
Vector2D Vector2D::PerpCW(void) {
Vector2D temp(-this->y, this->x);
return temp;
}
Vector2D Vector2D::PerpCCW(void) {
Vector2D temp(this->y, -this->x);
return temp;
}
Vector2D ClosestPointOnSegment(Vector2D P, Vector2D A, Vector2D B) {
Vector2D AB = B - A;
libnum::num32 t = AB.Dot(AB);
if (t == 0)
return A;
libnum::num32 t2 = (P.Dot(AB) - A.Dot(AB)) / t;
if (t2 < libnum::num32(0))
t2 = libnum::num32(0);
if (t2 > libnum::num32(1))
t2 = libnum::num32(1);
Vector2D C = A.Clone();
C.Add(AB, t2);
return C;
}