gpt4 book ai didi

objective-c - 检测线段是否与正方形相交

转载 作者:搜寻专家 更新时间:2023-10-30 19:40:54 26 4
gpt4 key购买 nike

有人对此有简单的算法吗?不需要旋转或任何东西。只是找出由两点构成的线段是否与正方形相交

最佳答案

这段代码应该可以解决问题。它检查线与边相交的位置,然后检查它是否在正方形的宽度范围内。返回相交数。

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;
}

注意:这段代码是理论上的,可能不正确,因为它还没有经过测试

关于objective-c - 检测线段是否与正方形相交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1354472/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com