使用以编程方式创建的ImageView检测碰撞

时间:2017-03-17 20:50:25

标签: ios objective-c uiimageview collision-detection

viewDidLoad中,我使用代码以编程方式创建了13个块:

for (int X = 1; X <= 13; X++) {
    UIImageView *iceBlockX = [[UIImageView alloc] initWithFrame:CGRectMake((28 * X - 4),52,28,28)];
    iceBlockX.image = [UIImage imageNamed:@"iceBlock.png"];

    iceBlockX.tag = X;

    [self.view insertSubview:iceBlockX belowSubview:_topPenguinCollisionTarget];
}

我需要检测在故事板(企鹅)上创建的imageView与任何一个以编程方式创建的imageView块之间的冲突。如果可以,那么用于检测的代码是什么?我尝试了以下代码,但它不起作用:

if (((CGRectIntersectsRect(_penguin.frame, _iceBlock1.frame)) && (_iceBlock1.hidden == NO)) ||
     ((CGRectIntersectsRect(_penguin.frame, _iceBlock2.frame)) &&(_iceBlock2.hidden == NO)) ||
     ((CGRectIntersectsRect(_penguin.frame, _iceBlock3.frame)) &&  (_iceBlock3.hidden == NO)) ||
     ((CGRectIntersectsRect(_penguin.frame, _iceBlock4.frame)) && (_iceBlock4.hidden == NO)) ||
     ((CGRectIntersectsRect(_penguin.frame, _iceBlock5.frame)) &&(_iceBlock5.hidden == NO)) ||
     ((CGRectIntersectsRect(_penguin.frame, _iceBlock6.frame)) && (_iceBlock6.hidden == NO)) || 
     ((CGRectIntersectsRect(_penguin.frame, _iceBlock7.frame)) && (_iceBlock7.hidden == NO)) || 
     ((CGRectIntersectsRect(_penguin.frame, _iceBlock8.frame)) && (_iceBlock8.hidden == NO)) || 
     ((CGRectIntersectsRect(_penguin.frame, _iceBlock9.frame)) && (_iceBlock9.hidden == NO)) || 
     ((CGRectIntersectsRect(_penguin.frame, _iceBlock10.frame)) && (_iceBlock10.hidden == NO)) ||
     ((CGRectIntersectsRect(_penguin.frame, _iceBlock11.frame)) && (_iceBlock11.hidden == NO)) ||
     ((CGRectIntersectsRect(_penguin.frame, _iceBlock12.frame)) && (_iceBlock12.hidden == NO)) ||
     ((CGRectIntersectsRect(_penguin.frame, _iceBlock13.frame)) &&(_iceBlock13.hidden == NO))) 
     {
    NSLog(@"A collision was detected");
}

1 个答案:

答案 0 :(得分:0)

如果“rect1”与“rect2”相交,则CGRectIntersectsRect返回true,否则返回false。

- (BOOL)didUIImageCollided{
  for (int X = 1; X <= 13; X++)
   {
     UIImageView *iceBlockX = (UIImageView*)[self.view viewWithTag:X];
     if(CGRectIntersectsRect(_penguin.frame, iceBlockX.frame))
     {
              return YES;
     }
  }
  return NO;
}