iOS CGRectIntersectsRect具有多个UIImageView实例



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

在这里,用户通过点击他们想要的位置在屏幕上创建多个"球",即名为"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在标头中声明为UIImageView):

    UIImageView *imgView;

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

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

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

但是,只有使用用户创建的LAST实例或"球"才能检测到交叉点。工作人员对这一点做出了反应,但对其余部分进行了评估。如果能帮助我修复代码以检测所有实例,我们将不胜感激。

每次创建新球时,都会覆盖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];
      }
   }

最新更新