Skip to content

Instantly share code, notes, and snippets.

@MathiasYde
Created December 17, 2022 17:35
Show Gist options
  • Save MathiasYde/baa89b61f8ca43ca07511fdf791fd683 to your computer and use it in GitHub Desktop.
Save MathiasYde/baa89b61f8ca43ca07511fdf791fd683 to your computer and use it in GitHub Desktop.
struct Vector3 {
union { float x; float r; };
union { float y; float g; };
union { float z; float b; };
// return a normalized vector
static Vector3 Normalize(const Vector3& v) {
float magnitude = Vector3::Magnitude(v);
return v * (1 / magnitude);
}
// return the magnitude of v
static float Magnitude(const Vector3& v) {
return std::sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
}
// return the dot product of a and b
static float DotProduct(const Vector3& a, const Vector3& b) {
return a.x * b.x + a.y * b.y + a.z * b.z;
}
// return the cross product of a and b
static Vector3 CrossProduct(const Vector3& a, const Vector3& b) {
return Vector3 {
a.y * b.z - a.z * b.y,
a.z * b.x - a.x * b.z,
a.x * b.y - a.y * b.x
};
}
Vector3 operator+(const Vector3& other) const {
return Vector3{
x + other.x,
y + other.y,
z + other.z,
};
}
Vector3 operator-(const Vector3& other) const {
return Vector3{
x - other.x,
y - other.y,
z - other.z,
};
}
// return a vector scaled by scalar
Vector3 operator*(const float& scalar) const {
return Vector3{
x * scalar,
y * scalar,
z * scalar,
};
}
friend std::ostream& operator<<(std::ostream& out, const Vector3& v) {
return (out << "Vector3(x=" << v.x << ", y=" << v.y << ", z=" << v.z << ")");
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment