【问题标题】:iOS CGRectIntersectsRect with multiple instances of UIImageView?具有多个 UIImageView 实例的 iOS CGRectIntersectsRect?
【发布时间】:2012-07-18 06:53:49
【问题描述】:

我有一个应用程序的布局,它需要检测图像何时与另一个图像发生碰撞。

在这里,用户通过点击他们想要的位置在屏幕上创建多个“球”,即名为“imgView”的 UIImageView 的同一个实例:

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *myTouch = [[event allTouches] anyObject];
    imgView = [[UIImageView alloc] initWithFrame:CGRectMake(40, 40, 40, 40)];
    imgView.image = [UIImage imageNamed:@"ball.png"];
    [self.view addSubview:imgView];
    imgView.center = [myTouch locationInView:self.view];

}

(imgView 在 header 中声明为 UIImageView):

    UIImageView *imgView;

现在,我还有一张名为“员工”的图片。它是一个在屏幕上水平平移的长条。我希望图像“工作人员”检测它与变量“imgView”或用户放置在屏幕上的球的每次碰撞。 因此,用户可以点击屏幕上的 10 个不同位置,并且“员工”应该能够捕捉到每一个位置。

我使用这个由 NSTimer 激活的 CGRectIntersectsRect 代码:

-(void)checkCollision {
    if( CGRectIntersectsRect(staff.frame,imgView.frame)) {
    [self playSound];
    }
}

但是,仅在最后一个实例或用户创建的“球”中检测到交叉点。工作人员对此做出了反应,但对其余部分进行了平移。任何帮助修复我的代码以检测所有实例将不胜感激。

【问题讨论】:

    标签: iphone objective-c ios sdk cgrect


    【解决方案1】:

    每次创建新球时,都会覆盖 imgView 实例变量。因此,您的checkCollision 方法只能看到imgView 的最新值,即最后创建的球。

    相反,您可以在NSArray 中跟踪屏幕上的每个球,然后检查与该数组中每个元素的碰撞。为此,请将您的 imgView 实例变量替换为:

    NSMutableArray *imgViews
    

    然后,在早期的某个时间,比如在viewDidLoad 中初始化数组:

     imgViews = [[NSMutableArray alloc] init]
    

    -touchesEnded:withEvent: 中将新的UIImageView 添加到数组中:

    - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    
         UITouch *myTouch = [[event allTouches] anyObject];
         UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(40, 40, 40, 40)];
         imgView.image = [UIImage imageNamed:@"ball.png"];
         [self.view addSubview:imgView];
         imgView.center = [myTouch locationInView:self.view];
         [imgViews addObject:imgView]
    }
    

    最后,在 checkCollision 中遍历您的数组并对每个元素执行检查

     - (void)checkCollision {
          for (UIImageView *imgView in imgViews) {
               if( CGRectIntersectsRect(staff.frame,imgView.frame)) {
                     [self playSound];
          }
       }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多