gpt4 book ai didi

iphone - 坐标中两条线的交点

转载 作者:太空狗 更新时间:2023-10-30 03:38:48 26 4
gpt4 key购买 nike

我可以检测两条线的交点,但如果我的线没有我屏幕的长度,它会检测到不应该在的点。

预览:Intersection所以,它不应该检测到这个交叉点,因为水平线没有那么长。

代码:

- (NSMutableArray *) intersectWithLines:(CGPoint)startPoint andEnd:(CGPoint)endPoint {
NSMutableArray *intersects = [[NSMutableArray alloc] init];

for(GameLine *line in [_lineBackground getLines]) {

double lineStartX = line.startPos.x;
double lineStartY = line.startPos.y;
double tempEndX = line.endPos.x;
double tempEndY = line.endPos.y;

double d = ((startPoint.x - endPoint.x)*(lineStartY - tempEndY)) - ((startPoint.y - endPoint.y) * (lineStartX - tempEndX));

if(d != 0) {
double sX = ((lineStartX - tempEndX) * (startPoint.x * endPoint.y - startPoint.y * endPoint.x) - (startPoint.x - endPoint.x) * (lineStartX * tempEndY - lineStartY * tempEndX)) / d;
double sY = ((lineStartY - tempEndY) * (startPoint.x * endPoint.y - startPoint.y * endPoint.x) - (startPoint.y - endPoint.y) * (lineStartX * tempEndY - lineStartY * tempEndX)) / d;


if([self isValidCGPoint:CGPointMake(sX, sY)]) {
[intersects addObject:[NSValue valueWithCGPoint:CGPointMake(sX, sY)]];
}
}
}

return intersects;
}

最佳答案

如果我正确理解你的问题,你需要确定两条线段的交点。这应该使用以下方法:

- (NSValue *)intersectionOfLineFrom:(CGPoint)p1 to:(CGPoint)p2 withLineFrom:(CGPoint)p3 to:(CGPoint)p4
{
CGFloat d = (p2.x - p1.x)*(p4.y - p3.y) - (p2.y - p1.y)*(p4.x - p3.x);
if (d == 0)
return nil; // parallel lines
CGFloat u = ((p3.x - p1.x)*(p4.y - p3.y) - (p3.y - p1.y)*(p4.x - p3.x))/d;
CGFloat v = ((p3.x - p1.x)*(p2.y - p1.y) - (p3.y - p1.y)*(p2.x - p1.x))/d;
if (u < 0.0 || u > 1.0)
return nil; // intersection point not between p1 and p2
if (v < 0.0 || v > 1.0)
return nil; // intersection point not between p3 and p4
CGPoint intersection;
intersection.x = p1.x + u * (p2.x - p1.x);
intersection.y = p1.y + u * (p2.y - p1.y);

return [NSValue valueWithCGPoint:intersection];
}

关于iphone - 坐标中两条线的交点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15690103/

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