所以我有一个名为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来检测碰撞?
谢谢你的时间!
答案 0 :(得分:3)
实际上,让我回答我自己的问题!
好的,所以我花了大约过去10个小时的时间环顾四周,我发现了这篇文章:Circle-Rectangle collision detection (intersection) - 看看e.James有什么要说的!
我写了一个函数来帮助解决这个问题:首先,声明以下struct
s:
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)));
}
我希望这有助于某人!
答案 1 :(得分:2)
CGRectIntersectsRect将始终使用矩形,视图的帧也将始终为矩形。你必须编写自己的函数。您可以使用视图的中心使用角半径计算圆,并测试矩形和圆以某种方式相交。