【问题标题】:Cocoa iOS Make a Rectangle into a Circle with CollisionsCocoa iOS 用碰撞将矩形变成圆形
【发布时间】:2012-07-01 00:48:53
【问题描述】:

所以我有一个名为 fallingBall 的 UIView,它目前与我的名为 theBlockView 的 UIView 很好地碰撞。我正在使用CGRectIntersectsRect(theBlockView.frame, fallingBall.frame) 来检测这种碰撞。

这一切都很好,所以现在我希望我的fallingBall 实际上是圆形的,我还希望theBlockView 的顶角是圆形的。为此,我使用了以下代码:

//round top right-hand corner of theBlockView
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:theBlockView.bounds 
                                           byRoundingCorners:UIRectCornerTopRight
                                           cornerRadii:CGSizeMake(10.0, 10.0)];
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = theBlockView.bounds;
maskLayer.path = maskPath.CGPath;
theBlockView.layer.mask = maskLayer;

//round the fallingBall view
[[fallingBall layer] setCornerRadius:30];

但是,有趣的是,虽然它们看起来很圆润,但视图仍然是矩形。 所以我的问题是:我怎样才能让CGRectIntersectsRect 将它们视为它们看起来的形状?是否有一个功能相同但使用视图的 alpha 来检测碰撞的功能?

感谢您的宝贵时间!

【问题讨论】:

    标签: objective-c ios cocoa-touch collision-detection quartz-2d


    【解决方案1】:

    其实,让我来回答我自己的问题吧!

    好的,所以我在过去 10 个小时的大部分时间里都在环顾四周,我发现了这个帖子:Circle-Rectangle collision detection (intersection) - 看看 e.James 怎么说!

    我写了一个函数来帮助解决这个问题:首先,声明以下structs:

    typedef struct
    {
        CGFloat x; //center.x
        CGFloat y; //center.y
        CGFloat r; //radius
    } Circle;
    typedef struct
    {
        CGFloat x; //center.x
        CGFloat y; //center.y
        CGFloat width;
        CGFloat height;
    } MCRect;
    

    然后添加如下函数:

    -(BOOL)circle:(Circle)circle intersectsRect:(MCRect)rect
    {
    
        CGPoint circleDistance = CGPointMake(abs(circle.x - rect.x), abs(circle.y - rect.y) );
    
        if (circleDistance.x > (rect.width/2 + circle.r)) { return false; }
        if (circleDistance.y > (rect.height/2 + circle.r)) { return false; }
    
        if (circleDistance.x <= (rect.width/2)) { return true; } 
        if (circleDistance.y <= (rect.height/2)) { return true; }
    
        CGFloat cornerDistance_sq = pow((circleDistance.x - rect.width/2), 2) + pow((circleDistance.y - rect.height/2), 2);
    
        return (cornerDistance_sq <= (pow(circle.r, 2)));
    }
    

    我希望这对某人有帮助!

    【讨论】:

      【解决方案2】:

      CGRectIntersectsRect 将始终使用矩形,视图的框架也将始终是矩形。您将不得不编写自己的函数。您可以使用视图的中心来使用角半径计算圆,并测试矩形和圆是否以某种方式相交。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-03-19
        • 2023-03-16
        • 1970-01-01
        • 2014-09-03
        • 2010-09-28
        • 2014-04-08
        • 2023-04-01
        相关资源
        最近更新 更多