Search code examples
iphoneobjective-ciosxcodecgrect

CGRect Collision With multiple CGRects


I am new in to iPhone programming, I am currently working on ballsplit game. In this game, when my bullet hits any ball ball, I want it to create two new balls. My bullet and ball are both uiimageview.

Here is my code:

if ((CGRectIntersectsRect(bullet.frame,Ball.frame)) && !(ball)){
    ball=TRUE;
    x=Ball.frame.origin.x;
    y=Ball.frame.origin.y;
    [self performSelector:@selector(createball)];
}

Here is my create ball function..

-(void)createball{
    if (ball) {
        imageMove1 = [[UIImageView alloc] initWithFrame:CGRectMake(x,y,50 ,50)];  
        UIImage *imag = [UIImage imageNamed:@"ball1.png"];
        [imageMove1 setImage:imag];
        [self.view addSubview:imageMove1];
        [ballArray addObject:imageMove1];

        imageMove2 = [[UIImageView alloc] initWithFrame:CGRectMake(x,y,50 ,50)]; 
        UIImage *imag1 = [UIImage imageNamed:@"ball1.png"];
        [imageMove2 setImage:imag1];
        [self.view addSubview:imageMove2];
        [ballArray addObject:imageMove2];
        ball=FALSE;
        [self performSelector:@selector(moveball)];
    }
}

Now after creating these two uiimgeview, when bullet hits one of these two uiimageview I want it to create another two uiimageviews. But problem that I face how we can get the frames of these new uiimageview...


Solution

  • After you move the bullet iterate trough array where you stored references to ball images:

    for (UIImageView *ball in ballArray){
         //check for collision
        if (CGRectIntersectsRect(bullet.frame,ball.frame)){
            //hit
        }
    }
    

    Check collision between balls:

    for (UIImageView *ballOne in ballArray){
        for (UIImageView *ballTwo in ballArray){
            //check for collision
            if (CGRectIntersectsRect(ballOne.frame,ballTwo.frame) && ballOne != ballTwo){
                //hit
            }
        }
    }