检查数组中对象之间冲突的好方法是什么?

Jas*_*son -1 arrays objective-c game-physics physics-engine ios

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

dea*_*rne 5

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

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

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

如果您还没有,可以尝试这样来优化内循环:

// 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];
}
Run Code Online (Sandbox Code Playgroud)