如何检测子视图之间的冲突?

时间:2013-05-24 18:56:11

标签: objective-c animation collision-detection collision layer

我目前使用两个类:Player和Ball(Monster类的儿子)。 使用d-pad,我可以在屏幕上移动玩家,并且球在屏幕上保持弹跳。 在ViewController中,我有一个NSMutableArray的玩家和一个NSMutableArray的球。

    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];
    }

如何检测球与球和球之间的碰撞? enter link description here

我尝试在VievController的viewDidLoad中调用此方法(checkCllisions),但它没有显示任何消息:

-(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");
        }
    }
}

1 个答案:

答案 0 :(得分:0)

collision方法的内部循环中有两个错误:您应该增加k而不是i,而monsters[i]应该是monsters[k]

请注意,可以简化CGRects的分配:

-(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");
        }
    }
}