shooter/engine/Vec2D.cpp

78 lines
1.5 KiB
C++
Raw Normal View History

//
// Created by Иван Ильин on 10.10.2021.
//
#include <cmath>
2021-10-31 11:39:08 +03:00
#include "Vec2D.h"
2021-10-28 16:58:02 +03:00
#include "Consts.h"
Vec2D::Vec2D(const Vec2D &vec) {
_arr_point[0] = vec.x();
_arr_point[1] = vec.y();
}
2021-10-31 11:39:08 +03:00
Vec2D::Vec2D(double x, double y) {
_arr_point[0] = x;
_arr_point[1] = y;
}
2021-10-28 16:58:02 +03:00
Vec2D::Vec2D(const Vec4D &point4D) {
_arr_point[0] = point4D.x();
_arr_point[1] = point4D.y();
}
Vec2D Vec2D::operator-() const {
return Vec2D(-x(), -y());
}
2021-10-31 11:39:08 +03:00
bool Vec2D::operator==(const Vec2D &vec) const {
return (*this - vec).sqrAbs() < Consts::EPS;
}
2021-10-31 11:39:08 +03:00
bool Vec2D::operator!=(const Vec2D &vec) const {
return !(*this == vec);
}
2021-10-31 11:39:08 +03:00
Vec2D Vec2D::operator+(const Vec2D &vec) const {
return Vec2D(x() + vec.x(), y() + vec.y());
}
2021-10-31 11:39:08 +03:00
Vec2D Vec2D::operator-(const Vec2D &vec) const {
2021-11-04 03:35:34 +03:00
return *this + -vec;
}
Vec2D Vec2D::operator*(double number) const {
2021-10-31 11:39:08 +03:00
return Vec2D(x() * number, y() * number);
}
Vec2D Vec2D::operator/(double number) const {
2021-10-31 11:39:08 +03:00
if (std::abs(number) > Consts::EPS) {
2021-11-04 03:35:34 +03:00
return *this * (1.0 / number);
2021-10-28 16:58:02 +03:00
} else {
throw std::domain_error{"Vec2D::operator/(double number): division by zero"};
2021-10-28 16:58:02 +03:00
}
}
// Other useful methods
double Vec2D::sqrAbs() const {
2021-10-31 11:39:08 +03:00
return x() * x() + y() * y();
}
double Vec2D::abs() const {
return sqrt(sqrAbs());
}
Vec2D Vec2D::normalized() const {
2021-11-04 03:35:34 +03:00
double vecAbs = sqrAbs();
2021-10-31 11:39:08 +03:00
if (vecAbs > Consts::EPS) {
2021-11-04 03:35:34 +03:00
return *this / sqrt(vecAbs);
2021-10-28 16:58:02 +03:00
} else {
return Vec2D(0);
2021-10-28 16:58:02 +03:00
}
}
2021-10-31 11:39:08 +03:00
double Vec2D::dot(const Vec2D &vec) const {
return vec.x() * x() + vec.y() * y();
}