检测线段是否与正方形相交 [英] Detect if line segment intersects square

查看:329
本文介绍了检测线段是否与正方形相交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人对此有一个简单的算法吗?无需旋转或任何其他操作.只是发现由两点组成的线段是否与正方形相交

Anyone have a simple algorithm for this? No need for rotation or anything. Just finding if a line segment made from two points intersects a square

推荐答案

此代码应能解决问题.它检查线与边相交的位置,然后检查其是否在正方形的宽度内.返回整数的数目.

This code should do the trick. It checks where the line intersects the sides, then checks if that is within the width of the square. The number of intesections is returned.

float CalcY(float xval, float x0, float y0, float x1, float y1)
{
    if(x1 == x0) return NaN;
    return y0 + (xval - x0)*(y1 - y0)/(x1 - x0);
}

float CalcX(float yval, float x0, float y0, float x1, float y1)
{
    if(x1 == x0) return NaN;
    return x0 + (yval - y0)*(y1 - y0)/(x1 - x0);
}

int LineIntersectsSquare(int x0, int y0, int x1, int y1, int left, int top, int right, int bottom)
{
    int intersections = 0;
    if(CalcX(bottom, x0, y0, x1, y1) < right && CalcX(bottom, x0, y0, x1, y1) > left  ) intersections++;
    if(CalcX(top   , x0, y0, x1, y1) < right && CalcX(top   , x0, y0, x1, y1) > left  ) intersections++;
    if(CalcY(left  , x0, y0, x1, y1) < top   && CalcY(left  , x0, y0, x1, y1) > bottom) intersections++;
    if(CalcY(right , x0, y0, x1, y1) < top   && CalcY(right , x0, y0, x1, y1) > bottom) intersections++;
    return intersections;
}

注意:此代码是理论性的,可能未经验证,因为它未经测试

NB: this code is theoretical and may not be correct, as it has not been tested

这篇关于检测线段是否与正方形相交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆