-1

我一直在另一个 for 循环中进行 for 循环,以便同时从数组中获取 2 个对象,但必须有更好的方法。我只想检查它们是否发生碰撞,然后将它们从视图和数组中删除。

4

4 回答 4

5

collide在你的问题中使用了这个词而没有告诉我们你的意思 - 这就是为什么到目前为止的其他答案没有帮助:)他们在谈论“字典/数组中的重复项目”中的碰撞,但你的意思是碰撞如overlay on the screen.

这可能是进行此测试的最糟糕的方式 - 当您获得大量图像时,它会迅速变得太慢。我不禁认为您正在尝试解决一个比我们任何一个都聪明得多的人已经解决的问题-您到底要做什么-也许完整的物理引擎可能是实现您的更好的方法最终目标?

例如,看看花栗鼠使用的空间散列数据结构- 这将创建一个包含所有对象的树 - 不在树的同一叶子中的对象不能碰撞,因此您可以快速减少比较。但是,该链接有一些图表比我在这里能更好地解释原理:)

如果你还没有,你可以试试这个来优化内部循环:

// Compare each image with the others to see if they overlap
NSMutableSet *colliding = [NSMutableSet new];
for (NSInteger indexA = 0; indexA < myImages.count; ++indexA) {
    UIView *a = [myImages objectAtIndex:indexA];
    CGRect rectA = a.frame;

    for (NSInteger indexB = indexA; indexB < myImages.count; ++indexB) {
        UIView *b = [myImages objectAtIndex:indexB];
        if (a==b) continue;

        CGRect rectB = b.frame;
        CGRect intersection = CGRectIntersect(rectA, rectB);
        if (NO == CGRectIsNull(intersection)) {
            [colliding addObject:a];
            [colliding addObject:b];
        }
    }
}

// Remove the colliding images
for (UIView *c in colliding) {
    [c removeFromSuperview];
    [myImages removeObject:c];
}
于 2012-10-09T12:16:24.050 回答
0

您可以使用NSCountedSet

NSArray *array = [[NSArray alloc] initWithObjects:@"1",@"1",@"0",nil];
NSCountedSet *set = [[NSCountedSet alloc] initWithArray:array];
NSLog(@"%@",set); // (1 [2], 0 [1]) // object 1 is collide 
for(id obj in set)
{
    if ([set countForObject:obj]>1) {
        //collide
    }
}
于 2012-10-09T12:08:09.303 回答
0

您是否正在寻找一种同时查找位于两个不同数组中的对象的方法?

如果是这样,我建议使用indexesOfObjectsPassingTest:of NSArray

@implementation NSArray (Comparison)
- (NSIndexSet *)indexesOfObjects:(NSArray *)objects {
    return [self indexesOfObjectsPassingTest:^(id obj, NSUInteger idx, BOOL *stop) {
        return [objects containsObject:obj];
    }];
}
- (NSArray *)objectsCommonWithArray:(NSArray *)array {
    return [self objectsAtIndexes:[self indexesOfObjects:array]];
}
@end

然后你可以这样做:

// assuming array1 and array2 exist.
NSArray *commonObjects = [array2 objectsCommonWithArray:array2];
于 2012-10-09T11:43:31.617 回答
0

NSArrays 有一个containsObject:方法可以用来代替内部循环。但是将一个对象中的所有对象放入一个集合 ( [NSSet setWithArray:]) 并遍历另一个数组,检查它们是否在集合中可能会更快(有人应该进行基准测试并查看)。或者将它们都转换并使用intersectSet:(在可变副本上)。我的猜测是,随着数组变大,set 方法会更快,但它不会对你拥有的数字产生影响。

于 2012-10-09T11:55:34.143 回答