【问题标题】:How to detect collisions between subviews?如何检测子视图之间的冲突?
【发布时间】:2013-05-24 18:56:11
【问题描述】:

我目前使用两个类: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");
        }
    }
}

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 仍然没有任何消息,谢谢我没有注意到 i++ 而不是 k++。有什么想法吗?
    • @Spale350z:您解决了两个问题吗? - 抱歉,我没有更好的主意。您可能必须对所有 CGRect 进行 NSLog() 以检查它们是否包含您期望的内容。
    • 好吧,刚刚意识到这一行不见了:[monsters addObject: m] 现在可以了,谢谢 Martin。
    猜你喜欢
    • 1970-01-01
    • 2014-05-31
    • 1970-01-01
    • 1970-01-01
    • 2015-08-09
    • 2012-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多