Search code examples
objective-canimationcollision-detectioncollisionlayer

How to detect collisions between subviews?


I currently use two classes: Player and Ball (son of Monster class). With a d-pad i can move the players on the screen and the ball keep bouncing in the screen. In the ViewController i have a NSMutableArray of players and a NSMutableArray of balls.

    Player *m = [[Car alloc]init];
    [players addObject:m];
    [self.view addSubview:m.image];

    joypad = [[Joypad alloc] initWithPlayer:players[0]];
    [self.view addSubview: joypad.pad];
    [self.view addSubview:joypad.movingPad];


    monsters = [NSMutableArray arrayWithCapacity:MAX];
    for(int i = 0; i < MAX; ++i)
    {
        int radius = rand()%100;
        int deltax = rand()%5 + 1;
        int deltay = rand()%5 +1;
        Monster *ball = [[Ball alloc] initWithRadius:radius andDX:deltax DY:deltay];
        [self.view addSubview:ball.image];
        [ball startMoving];
    }

How can i detect collisions between balls with balls and balls with players? enter link description here

I tried by calling this method (checkCllisions) in the VievController's viewDidLoad but it doesn't show any message:

-(void) checkCollisions{
    [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(collisions) userInfo:nil repeats:YES];
}

-(void) collisions{

    for(int i = 0; i < [players count]; i++){
        Player *p = players[i];
        CGRect f = CGRectMake(p.image.frame.origin.x, p.image.frame.origin.y, p.image.frame.size.width, p.image.frame.size.height);
        for (int k = 0; k < [monsters count]; i++){
            Monster *m = monsters[i];
            CGRect fm = CGRectMake(m.image.frame.origin.x, m.image.frame.origin.y, m.image.frame.size.width, m.image.frame.size.height);
            if(CGRectIntersectsRect(f, fm))
                NSLog(@"collision");
        }
    }
}

Solution

  • There are two errors in the inner loop of the collision method: You should increment k instead of i, and monsters[i] should be monsters[k].

    Note that the assignment of the CGRects can be simplified:

    -(void) collisions{
        for(int i = 0; i < [players count]; i++){
            Player *p = players[i];
            CGRect f = p.image.frame;
            for (int k = 0; k < [monsters count]; k++){
                Monster *m = monsters[k];
                CGRect fm = m.image.frame;
                if(CGRectIntersectsRect(f, fm))
                    NSLog(@"collision");
            }
        }
    }