calculating distance between a point and a rectangular box (nearest point)

前端 未结 9 1743
广开言路
广开言路 2020-12-13 06:25

is there a easy formula to calculate this? i\'ve been working on some math but i can only find a way to calculate the distance directed to the center of the box, not direct

9条回答
  •  误落风尘
    2020-12-13 06:55

    This is easy to achieve with dot products. In fact it has been answered in 3d already for the non axis aligned case.

    https://stackoverflow.com/a/44824522/158285

    But in 2D you can achieve the same

    public struct Vector2 {
       double X; double Y
    
       // Vector dot product
       double Dot(Vector2 other)=>X*other.X+Y*other.Y;
    
    
       // Length squared of the vector
       double LengthSquared()=>Dot(this,this);
    
       // Plus other methods for multiplying by a scalar
       // adding and subtracting vectors etc
    }
    

    The function to return the closest point

    public Vector2 ClosestPointTo
        (Vector2 q, Vector2 origin, Vector3 v10, Vector3 v01)
    {
        var px = v10;
        var py = v01;
    
    
        var vx = (px - origin);
        var vy = (py - origin);
    
    
        var tx = Vector2.Dot( q - origin, vx ) / vx.LengthSquared();
        var ty = Vector3.Dot( q - origin, vy ) / vy.LengthSquared();
    
    
        tx = tx < 0 ? 0 : tx > 1 ? 1 : tx;
        ty = ty < 0 ? 0 : ty > 1 ? 1 : ty;
    
        var p = tx * vx + ty * vy + origin;
    
        return p;
    }
    

提交回复
热议问题