ForesightMiningSoftwareCorporation / bevy_transform_gizmo

A 3d gizmo for transforming entities in Bevy.
Apache License 2.0
162 stars 40 forks source link

Use more robust math for translation #27

Open aevyrie opened 2 years ago

aevyrie commented 2 years ago

Instead of the plane intersection method, should use vector math for finding the nearest point on skew vectors, something like:

pub fn nearest_point(&self, other: &Ray) -> Option<Vec3> {
    let delta_p = other.origin - self.origin;
    let v1_squared = self.direction.dot(self.direction);
    let v2_squared = other.direction.dot(other.direction);
    let v1_dot_v2 = self.direction.dot(other.direction);
    let determinant = v1_dot_v2.powi(2) - v1_squared * v2_squared;

    if determinant.abs() > f32::MIN {
        let delta_p_v1 = delta_p.dot(self.direction);
        let delta_p_v2 = delta_p.dot(other.direction);
        let t = (1.0 / determinant) * (v2_squared * delta_p_v1 - v1_dot_v2 * delta_p_v2);
        let result = self.origin + self.direction * t;
        Some(result)
    } else {
        // The lines are parallel!
        None
    }
}

This should be more robust to camera view changes and translating at far distances with perspective cameras.