separating axis test——分离轴测试算法的实现

iOS开发判断两个旋转后的矩形是否相交

开发过程中需要解决任意操作的两个任意旋转的矩形相交的问题,面向google编程后发现新的理论知识:separating axis test。
简单了解后实现了该功能。感谢强大的数学知识。

理论知识:

请添加图片描述

OC实现

// both rects must be specified as all four points, clockwise from top-left point
// their points must already be rotated and specified in global space before passing to this function
- (BOOL)isRectIntersectWithRectA:(NSArray <NSValue *>*)r1 rectB:(NSArray <NSValue*>*)r2 {
    if (!r1 || !r2) {
        NSLog(@"Rects are not accessible");
        return NO;
    }

    NSInteger pn, px;
    for (NSInteger pi = 0, pl = r1.count; pi < pl; pi += 1) {
        pn = (pi == (pl - 1)) ? 0 : pi + 1; // next point
        px = (pn == (pl - 1)) ? 0 : pn + 1;
        
        CGPoint pointPi = [r1[pi] CGPointValue];
        CGPoint pointPn = [r1[pn] CGPointValue];
        CGPoint pointPx = [r1[px] CGPointValue];
        
        BOOL result = [self edgeTestWithPoint1:pointPi point2:pointPn point3:pointPx rect2:r2];
        if (result) {
            return NO;
        }
    }
        
    for (NSInteger pi = 0, pl = r2.count; pi < pl; pi += 1) {
        pn = (pi == (pl - 1)) ? 0 : pi + 1; // next point
        px = (pn == (pl - 1)) ? 0 : pn + 1;
        
        CGPoint pointPi = [r2[pi] CGPointValue];
        CGPoint pointPn = [r2[pn] CGPointValue];
        CGPoint pointPx = [r2[px] CGPointValue];
        
        BOOL result = [self edgeTestWithPoint1:pointPi point2:pointPn point3:pointPx rect2:r1];
        if (result) {
            return NO;
        }
    }

    return YES;
}

-(BOOL)edgeTestWithPoint1:(CGPoint)p1 point2:(CGPoint)p2 point3:(CGPoint)p3 rect2:(NSArray <NSValue *>*)r2 {
    CGPoint rot = CGPointMake(-(p2.y - p1.y), p2.x - p1.x);
    
    BOOL ref = (rot.x * (p3.x - p1.x) + rot.y * (p3.y - p1.y)) >= 0;

    for (NSInteger i=0; i<r2.count; i++) {
        CGPoint point = [r2[i] CGPointValue];
        if ((rot.x * (point.x-p1.x) + rot.y * (point.y-p1.y)) >= 0 == ref) {
            return NO;
        }
    }

    return YES;
}

参考资源:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jarlen John

谢谢你给我一杯咖啡的温暖

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值