C++ 矩形相交判断代码解析
这段代码是用来判断两个矩形是否相交的。首先判断两个矩形的四个边是否有重叠,如果没有重叠则返回'false'。如果有重叠,则计算出两个矩形中心点之间的偏移量,并用偏移量和矩形的长度和宽度来判断两个矩形是否相交。如果相交,则返回'true',否则返回'false'。
if (box.max_x() < min_x() || box.min_x() > max_x() || box.max_y() < min_y() ||
box.min_y() > max_y()) {
return false;
}
const double shift_x = box.center_x() - center_.x();
const double shift_y = box.center_y() - center_.y();
const double dx1 = cos_heading_ * half_length_;
const double dy1 = sin_heading_ * half_length_;
const double dx2 = sin_heading_ * half_width_;
const double dy2 = -cos_heading_ * half_width_;
const double dx3 = box.cos_heading() * box.half_length();
const double dy3 = box.sin_heading() * box.half_length();
const double dx4 = box.sin_heading() * box.half_width();
const double dy4 = -box.cos_heading() * box.half_width();
return std::abs(shift_x * cos_heading_ + shift_y * sin_heading_) <=
std::abs(dx3 * cos_heading_ + dy3 * sin_heading_) +
std::abs(dx4 * cos_heading_ + dy4 * sin_heading_) +
half_length_ &&
std::abs(shift_x * sin_heading_ - shift_y * cos_heading_) <=
std::abs(dx3 * sin_heading_ - dy3 * cos_heading_) +
std::abs(dx4 * sin_heading_ - dy4 * cos_heading_) +
half_width_ &&
std::abs(shift_x * box.cos_heading() + shift_y * box.sin_heading()) <=
std::abs(dx1 * box.cos_heading() + dy1 * box.sin_heading()) +
std::abs(dx2 * box.cos_heading() + dy2 * box.sin_heading()) +
box.half_length() &&
std::abs(shift_x * box.sin_heading() - shift_y * box.cos_heading()) <=
std::abs(dx1 * box.sin_heading() - dy1 * box.cos_heading()) +
std::abs(dx2 * box.sin_heading() - dy2 * box.cos_heading()) +
box.half_width();
代码首先判断两个矩形的四个边是否有重叠,如果没有重叠则返回'false'。这一步是通过比较两个矩形的最值坐标来实现的。
如果两个矩形的边界有重叠,则代码会计算两个矩形中心点之间的偏移量。然后,代码会根据偏移量和矩形的长度和宽度来判断两个矩形是否相交。判断相交的逻辑是比较两个矩形的中心点偏移量是否小于等于两个矩形的长度和宽度之和。
代码中涉及的一些变量的含义如下:
box: 表示另一个矩形。center_: 表示第一个矩形的中心点。half_length_: 表示第一个矩形的长度的一半。half_width_: 表示第一个矩形的宽度的一半。cos_heading_: 表示第一个矩形的方向角的余弦值。sin_heading_: 表示第一个矩形的方向角的正弦值。
这段代码使用了向量和三角函数来计算矩形的中心点偏移量和判断两个矩形是否相交。代码的逻辑清晰易懂,而且效率较高。
原文地址: https://www.cveoy.top/t/topic/owMx 著作权归作者所有。请勿转载和采集!