I have a layout for an application that needs to detect when an image collides with another image.
Here, the user creates multiple ‘balls’, the same instance of a UIImageView named ‘imgView’, on the screen by tapping the location they desire:
- (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 is declared as a UIImageView in the header) :
UIImageView *imgView;
Now, I also have an image called ‘staff’. It is a long bar that pans horizontally across the screen. I want the image ‘staff’ to detect EVERY collision it has with the variable ‘imgView’, or the balls the user has placed on the screen.
Therefore, the user could tap 10 different places on the screen and and ‘staff’ should be able to catch every single one.
I use this CGRectIntersectsRect code thats activated by an NSTimer:
-(void)checkCollision {
if( CGRectIntersectsRect(staff.frame,imgView.frame)) {
[self playSound];
}
}
However, the intersection is only detected with the LAST instance, or ‘ball’ the user created. The staff reacts to that one, but pans over the rest. Any help to fix my code to detect all instances would be greatly appreciated.
Each time you create a new ball, you are overriding your
imgViewinstance variable. Thus, yourcheckCollisionmethod only sees the latest value ofimgView, namely the last ball created.Instead, you could keep track of every ball on screen in an
NSArray, then check for collisions against every element in that array. To do that, replace yourimgViewinstance variable with, say:Then, sometime early on, say in
viewDidLoadinitialize the array:In
-touchesEnded:withEvent:add the newUIImageViewto the array:And finally, in
checkCollisioniterate through your array and perform your check on every element