iphone-如何检查NSMutablearray中元素之间的冲突?

时间:2013-08-02 00:20:53

标签: objective-c cocoa-touch nsmutablearray

背景:我正在使用XCode 3.1。请不要对此发表评论。

问题:我有两个按钮,fire和make meteor,点击后会生成UIImageViews。我将这些UIImageviews添加到两个单独的NSMutable数组,子弹和流星。如何检查项目符号数组中的任何元素与流星阵列中的元素之间的冲突。此外,如果发生碰撞,我将如何从视图中移除子弹和有问题的流星。谢谢。到目前为止,这是我的代码:

-(IBAction)createBullets:(id)sender{
        UIImageView *two = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"lazerBeam.png"]];
    CGRect rectTwo = CGRectMake((image.center.x), (image.center.y - 45), 7, 20);
    [two setFrame:rectTwo];
    [self.view addSubview:two];
    [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(moveBulletOne:) userInfo:two repeats:YES];
    [bulletImageViews addObject:two]; 
}

-(IBAction)createMeteors:(id)sender{

    UIImageView *one = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"Meteor.png"]];
    CGRect rectOne = CGRectMake(arc4random() % (310), arc4random() % (1), 35, 35);
    [one setFrame:rectOne];
    [self.view addSubview:one];
    [NSTimer scheduledTimerWithTimeInterval:0.4 target:self selector:@selector(moveMeteorOne:) userInfo:one repeats:YES];
    [meteorImageViews addObject:one];



}

我也使用NSTimer将流星和子弹移动到移动功能,但这无关紧要。基本上,我想检查子弹何时与流星碰撞,当发生这种情况时,从视图中移除有问题的流星和子弹。

1 个答案:

答案 0 :(得分:3)

基本O(n ^ 2)搜索,检查每颗流星的每颗子弹。对于小型应用程序来说这可能很好,但可以使用空间分区方法对其进行优化,以减少所需的检查量(四叉树等)。您希望创建一个“toRemove”数组,而不是在适当的位置删除,以便在枚举时不修改数组。

NSMutableArray* bulletsToRemove = [NSMutableArray array];
NSMutableArray* meteorsToRemove = [NSMutableArray array];

    for (UIImageView* bullet in bulletImageViews)
    {
        for (UIImageView* meteor in meteorImageViews)
        {
            if (CGRectIntersectsRect(bullet.frame, meteor.frame)
            {
                 [bulletsToRemove addObject:bullet];
                 [meteorsToRemove addObject:meteor];
                 break;
            }
         }
    }

[bulletsToRemove makeObjectsPerformSelector:@selector(removeFromSuperview)];
[meteorsToRemove makeObjectsPerformSelector:@selector(removeFromSuperview)];

[bulletImageViews removeObjectsInArray:bulletsToRemove];
[meteorImageViews removeObjectsInArray:meteorsToRemove];