How to calculate distance between two rectangles? (Context: a game in Lua.)

后端 未结 8 1537
梦毁少年i
梦毁少年i 2020-12-15 17:53

Given two rectangles with x, y, width, height in pixels and a rotation value in degrees -- how do I calculate the closest distance of their outlines toward each other?

8条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-15 18:24

    I just wrote the code for that in n-dimensions. I couldn't find a general solution easily.

    // considering a rectangle object that contains two points (min and max)
    double distance(const rectangle& a, const rectangle& b) const {
        // whatever type you are using for points
        point_type closest_point;
        for (size_t i = 0; i < b.dimensions(); ++i) {
            closest_point[i] = b.min[i] > a.min[i] ? a.max[i] : a.min[i];
        }
        // use usual euclidian distance here
        return distance(a, closest_point);
    }
    

    For calculating the distance between a rectangle and a point you can:

    double distance(const rectangle& a, const point_type& p) const {
        double dist = 0.0;
        for (size_t i = 0; i < dimensions(); ++i) {
            double di = std::max(std::max(a.min[i] - p[i], p[i] - a.max[i]), 0.0);
            dist += di * di;
        }
        return sqrt(dist);
    }
    

    If you want to rotate one of the rectangles, you need to rotate the coordinate system.

    If you want to rotate both rectangles, you can rotate the coordinate system for rectangle a. Then we have to change this line:

    closest_point[i] = b.min[i] > a.min[i] ? a.max[i] : a.min[i];
    

    because this considers there is only one candidate as the closest vertex in b. You have to change it to check the distance to all vertexes in b. It's always one of the vertexes.

    See: https://i.stack.imgur.com/EKJmr.png

提交回复
热议问题