-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVector3.cpp
More file actions
107 lines (88 loc) · 2.02 KB
/
Vector3.cpp
File metadata and controls
107 lines (88 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
//
// Created by redkc on 19/10/2023.
//
#include <stdexcept>
#include <cmath>
#include "Vector3.h"
void Vector3::operator+=(const Vector3 &v) {
x += v.x;
y += v.y;
z += v.z;
}
void Vector3::operator-=(const Vector3 &v) {
x -= v.x;
y -= v.y;
z -= v.z;
}
void Vector3::operator*=(float f) {
x *= f;
y *= f;
z *= f;
}
void Vector3::operator/=(float f) {
if (f != 0) {
x /= f;
y /= f;
z /= f;
} else {
throw std::runtime_error("Division by zero error in Vector3 operator /="); // throw an exception
}
}
float Vector3::length() const {
return sqrtf(powf(x, 2) + powf(y, 2) + powf(z, 2));
}
void Vector3::normalize() {
float n = length();
if (n != 0) {
operator/=(n);
} else {
throw std::runtime_error("Division by zero error in Vector3 normalize"); // throw an exception
}
}
Vector3 Vector3::dot(const Vector3 &v) const {
Vector3 dotResult;
dotResult.x = x * v.x;
dotResult.y = y * v.y;
dotResult.z = x * v.z;
return dotResult;
}
float Vector3::dotProduct(const Vector3 &v) const {
return x * v.x + y * v.y + z * v.z;
}
Vector3 Vector3::cross(const Vector3 &v) const {
return Vector3( y * v.z - z * v.y,
z * v.x - x * v.z,
x * v.y - y * v.x);
}
bool Vector3::operator==(const Vector3 &v) const {
return (x == v.x && y == v.y && z == v.z);
}
std::string Vector3::toString() const {
std::ostringstream oss;
oss << "(" << x << ", " << y << ", " << z << ")";
return oss.str();
}
Vector3 Vector3::operator+(const Vector3 &v) const {
return {
x + v.x,
y + v.y,
z + v.z};
}
Vector3 Vector3::operator-(const Vector3 &v) const {
return {
x - v.x,
y - v.y,
z - v.z};
}
Vector3 Vector3::operator*(float f) const {
return {
x * f,
y * f,
z * f};
}
Vector3 Vector3::operator/(float f) const {
return {
x / f,
y / f,
z / f};
}