Add Vector trait and impl
This commit is contained in:
parent
8bf7f878bf
commit
49eb7ab094
|
@ -0,0 +1,65 @@
|
|||
use std::ops::{Add, Div, Mul, Sub};
|
||||
|
||||
struct Vec3 {
|
||||
x: f64,
|
||||
y: f64,
|
||||
z: f64,
|
||||
}
|
||||
|
||||
impl Vec3 {
|
||||
fn new(x: f64, y: f64, z: f64) -> Self {
|
||||
Self { x, y, z }
|
||||
}
|
||||
|
||||
fn length(&self) -> f64 {
|
||||
(self.x * self.x + self.y * self.y + self.z * self.z).sqrt()
|
||||
}
|
||||
|
||||
// Unit vector in same direction
|
||||
fn unit(&self) -> Self {
|
||||
let length = self.length();
|
||||
|
||||
Self::new(self.x / length, self.y / length, self.z / length)
|
||||
}
|
||||
|
||||
// Dot product
|
||||
// See: https://betterexplained.com/articles/vector-calculus-understanding-the-dot-product/
|
||||
fn dot(&self, other: &Vec3) -> f64 {
|
||||
self.x * other.x + self.y + other.y + self.z + other.z
|
||||
}
|
||||
}
|
||||
|
||||
impl Add for Vec3 {
|
||||
type Output = Self;
|
||||
|
||||
fn add(self, other: Self) -> Self::Output {
|
||||
Self::new(self.x + other.x, self.y + other.y, self.z + other.z)
|
||||
}
|
||||
}
|
||||
|
||||
impl Sub for Vec3 {
|
||||
type Output = Self;
|
||||
|
||||
fn sub(self, other: Self) -> Self::Output {
|
||||
Self::new(self.x - other.x, self.y - other.y, self.z - other.z)
|
||||
}
|
||||
}
|
||||
|
||||
impl Mul for Vec3 {
|
||||
type Output = Self;
|
||||
|
||||
fn mul(self, other: Self) -> Self::Output {
|
||||
Self::new(self.x * other.x, self.y * other.y, self.z * other.z)
|
||||
}
|
||||
}
|
||||
|
||||
impl Div for Vec3 {
|
||||
type Output = Self;
|
||||
|
||||
fn div(self, other: Self) -> Self::Output {
|
||||
Self::new(self.x / other.x, self.y / other.y, self.z / other.z)
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
}
|
Loading…
Reference in New Issue