Skip to content

Commit

Permalink
v3: vector normalization
Browse files Browse the repository at this point in the history
  • Loading branch information
jcornaz committed Aug 7, 2023
1 parent 2bd7464 commit ac8bfb1
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/v3/math.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,14 @@ impl Vec2 {
pub fn magnitude(self) -> f32 {
self.magnitude_squared().sqrt()
}

fn normalize(self) -> Option<Self> {
let normal = self / self.magnitude();
if !normal.x.is_finite() {
return None;
}
Some(normal)
}
}

impl AddAssign for Vec2 {
Expand Down Expand Up @@ -195,4 +203,20 @@ mod tests {
expected_magnitude * expected_magnitude
);
}

#[rstest]
fn normalize_zero_returns_none() {
assert_eq!(Vec2::ZERO.normalize(), None);
}

#[rstest]
#[case(Vec2::X, Vec2::X)]
#[case(-Vec2::X, -Vec2::X)]
#[case(Vec2::Y, Vec2::Y)]
#[case(Vec2::X * 2.0, Vec2::X)]
#[case(Vec2::Y * 2.0, Vec2::Y)]
#[case(Vec2::new(3.0, 4.0), Vec2::new(0.6, 0.8))]
fn normalize_returns_expected(#[case] vector: Vec2, #[case] expected: Vec2) {
assert_abs_diff_eq!(vector.normalize().unwrap(), expected);
}
}

0 comments on commit ac8bfb1

Please sign in to comment.