Add Vector trait and impl

This commit is contained in:
Michael Kohl 2021-05-14 18:03:27 +07:00
parent 8bf7f878bf
commit 49eb7ab094
1 changed files with 65 additions and 0 deletions

65
src/main.rs Normal file
View File

@ -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() {
}