0

背景:我正在使用 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 将流星和子弹移动到移动功能,但这无关紧要。基本上,我想检查子弹何时与流星碰撞,以及何时发生这种情况,以便从视图中移除有问题的流星和子弹。

4

1 回答 1

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];
于 2013-08-02T00:27:04.177 回答