Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // nalgebra shim. the playground should really support it though
- pub mod na {
- pub struct Vector2<T> {
- pub x: T,
- pub y: T,
- }
- impl<T> Vector2<T> {
- pub fn new(x: T, y: T) -> Self {
- Vector2 {
- x,
- y
- }
- }
- }
- }
- pub const FLOAT_ERROR_ABS: f32 = 0.0001;
- /// this function takes two vectors and compares only their direction, not
- /// their length. if the direction of both vectors is equal, this function
- /// returns true, otherwise false.
- /// the dot product is not what I want, as it is positive if two vectors are
- /// parallel, which means vectors thac point in the exact opposite direction
- /// of each other will pass, which is not what I want.
- pub fn direction_eq(v1: &na::Vector2<f32>, v2: &na::Vector2<f32>) -> bool {
- // there may be a more efficient way to do this. it works good enough for
- // now though.
- // the x and y deltas of both vectors must both be positive or negative.
- // because 0.0 can be negative or positive, we do not use
- // `is_sign_positive`
- if !( (v1.x >= 0.0) == (v2.x >= 0.0) || (v1.y >= 0.0) == (v2.y >= 0.0) ) {
- return false;
- }
- let x = v1.x / v2.x;
- if x.is_nan() {
- return true;
- }
- let y = v1.y / v2.y;
- if y.is_nan() {
- return true;
- }
- (x - y).abs() < FLOAT_ERROR_ABS
- }
- fn main() {
- assert_eq!(true, direction_eq(&na::Vector2::new(1.0, 1.0), &na::Vector2::new(1.0, 1.0)));
- assert_eq!(true, direction_eq(&na::Vector2::new(1.0, 1.0), &na::Vector2::new(2.0, 2.0)));
- assert_eq!(true, direction_eq(&na::Vector2::new(-1.0, -1.0), &na::Vector2::new(-2.0, -2.0)));
- assert_eq!(true, direction_eq(&na::Vector2::new(1.0, -1.0), &na::Vector2::new(2.0, -2.0)));
- assert_eq!(true, direction_eq(&na::Vector2::new(-1.0, 1.0), &na::Vector2::new(-2.0, 2.0)));
- assert_eq!(true, direction_eq(&na::Vector2::new(2.0, 2.0), &na::Vector2::new(1.0, 1.0)));
- assert_eq!(true, direction_eq(&na::Vector2::new(0.000005, 0.0003), &na::Vector2::new(0.05, 3.0)));
- assert_eq!(true, direction_eq(&na::Vector2::new(1.0, 0.0), &na::Vector2::new(2.0, 0.0)));
- assert_eq!(true, direction_eq(&na::Vector2::new(0.0, 1.0), &na::Vector2::new(0.0, 3.0)));
- assert_eq!(true, direction_eq(&na::Vector2::new(-1.0, 1.0), &na::Vector2::new(-1.0, 1.0)));
- assert_eq!(false, direction_eq(&na::Vector2::new(1.0, 1.0), &na::Vector2::new(0.0, 3.0)));
- assert_eq!(false, direction_eq(&na::Vector2::new(1.0, 1.0), &na::Vector2::new(1.0, 2.0)));
- assert_eq!(false, direction_eq(&na::Vector2::new(1.0, 1.0), &na::Vector2::new(2.0, 1.0)));
- assert_eq!(false, direction_eq(&na::Vector2::new(1.0, 1.0), &na::Vector2::new(-1.0, -1.0)));
- assert_eq!(false, direction_eq(&na::Vector2::new(-1.0, 1.0), &na::Vector2::new(1.0, -1.0)));
- assert_eq!(false, direction_eq(&na::Vector2::new(1.0, -1.0), &na::Vector2::new(-1.0, 1.0)));
- println!("!dlrow olleh");
- }
Add Comment
Please, Sign In to add comment