圆与矩形的碰撞检测

适用于矩形不旋转的情况

// 圆与矩形的碰撞检测(适用于矩形无旋转的情况下)
- (BOOL)collisionDetectionCircleCenter:(CGPoint)cPoint radius:(CGFloat)radius toRectangle:(CGRect)rect {
    CGFloat width = rect.size.width;
    CGFloat height = rect.size.height;
    // 圆心与矩形中心的相对距离
    CGFloat relativeX = cPoint.x - (rect.origin.x + width * 0.5);
    CGFloat relativeY = cPoint.y - (rect.origin.y + height * 0.5);
    
    CGFloat dx = MIN(relativeX, (width * 0.5));
    CGFloat dx1 = MAX(dx, (-width * 0.5));
    CGFloat dy = MIN(relativeY, (height * 0.5));
    CGFloat dy1 = MAX(dy, (-height * 0.5));
    
    BOOL isCollision = (dx1 - relativeX) * (dx1 - relativeX) + (dy1 - relativeY) * (dy1 - relativeY) <= radius * radius;
    return isCollision;
}

你可能感兴趣的:(圆与矩形的碰撞检测)