如何检测2个UIViews之间的碰撞

时间:2014-03-13 00:26:32

标签: ios uiimageview detect collision

我有一个包含我的主角色的UIImageView,我已经让UIImageView出现了圆形,见下面的代码用于创建我的角色

copter = [[UIImageView alloc] initWithFrame:CGRectMake(100, 500, 90, 90)];
[copter setContentMode:UIViewContentModeScaleAspectFit];
copter.layer.cornerRadius = roundf(copter.frame.size.width/2.0);
copter.layer.masksToBounds = YES;
[copter startAnimating];
[[self view] addSubview:copter];
[self setBat:copter];

我在角色和游戏中的其他物体之间碰撞时遇到了麻烦。在矩形而不是圆上检测到碰撞。我到处寻找答案来解决这个问题,但没有运气。

这是我正在使用的碰撞代码:

 self.batVelocity += [link duration]*FBDownardBatAccelerationIpad;

 [[self copter] setFrame:CGRectOffset([[self copter] frame], 0, [self batVelocity])];

 UIView *removeBlock = nil;
 for (UIView *block in [self blocks]) {
      [block setFrame:CGRectOffset([block frame], [link duration]*FBSidewaysVelocityIpad, 0)];
       if (CGRectIntersectsRect([[self copter] frame], [block frame])) {
             [self failed];

所以基本上我需要角色的圆形边界与一个矩形对象碰撞,而不是圆圈所在的矩形边界。我希望这是有道理的。

提前致谢

2 个答案:

答案 0 :(得分:1)

我使用的是CGPathRef或CGMutablePathRef。因此,正如@ user3386109建议的那样,首先检查rects之间的冲突,然后如果你有精灵的pathRef或者它是什么,你可以使用CGPathContainsPoint()。 Quartz还为Rects的CGPathRef提供了一些其他比较函数,并且为了将路径与第二个路径进行比较,请检查文档。我发现CGPathRef非常有效,但是不要忘记使用CGPathRelease()来释放它以匹配每个CGPathCreate或CGPathCopy()函数,否则泄漏可以快速加起来..

答案 1 :(得分:0)

是的,首先你要检查重叠的矩形(你已经完成了)。当您发现重叠时,则需要优化碰撞测试。对于有问题的矩形的每个角,计算从角色中心到有问题矩形角的距离。如果从中心到任何角的距离小于圆的半径,那么就会发生碰撞。为了稍微优化代码,计算(dx * dx + dy * dy)并将其与半径平方进行比较。这样你就不必计算任何平方根。

进一步审核后,除角落检查外,还需要进行边缘检查。例如,如果顶部y值高于圆心,而底部y值低于圆心,则计算左边矩形之间x的差值边缘和圆心,如果该距离小于半径,则发生碰撞。同样,对于矩形的其他三个边缘。

这里有一些用于角落检查的伪代码

int dx, dy, radius, radiusSquared;

radiusSquared = radius * radius;
for ( each rectangle that overlaps the player rectangle )
{
    for ( each corner of the rectangle )
    {
        dx = corner.x - center.x;
        dy = corner.y - center.y;
        if ( dx * dx + dy * dy < radiusSquared )
            Collision!!!
    }
}
相关问题