UIImageViews碰撞的问题

时间:2011-09-22 15:36:27

标签: iphone arrays xcode uiimageview collision-detection

-(void)moveTheImage{
for (NSUInteger i = 0; i < [views count]; i++) {
    image = [views objectAtIndex:i];
    X = [[XArray objectAtIndex:i] floatValue];
    Y = [[YArray objectAtIndex:i] floatValue];
image.center=CGPointMake(image.center.x + X, image.center.y + Y);


    if(!intersectFlag)
    {    

        if(CGRectIntersectsRect(image.frame,centre.frame))    
        {
            intersectFlag = YES;    
            label.text= [NSString stringWithFormat:@"%d", count];

            ++count;
        }


    }
    else
    {
        if(!CGRectIntersectsRect(image.frame,centre.frame))
        {
            intersectFlag = NO;
        }
    }


}

我希望每次“图像”与“中心”相交时计数增加为1,但是当发生碰撞时,计数会非常快地增长,直到“图像”不接触“中心”。更确切地说,“图像”移动然后通过“中心”并且计数增加,并且当“图像”不与“中心”接触时,计数器停止。如何我解决这个问题?对不起我的英语我是法国人:/

1 个答案:

答案 0 :(得分:0)

正如我在最后一条评论中所说,我认为你的计数问题是因为帧速率。

所以你可以使用NSMutableSet来包含碰撞中的所有物体。

在界面中,您声明新的集合:

NSMutableSet * collisionObjects;

在init方法中:

collisionObjects = [[NSMutableSet alloc] init];

在dealloc中:

[collisionObjects release];

你的方法变成了:

-(void)moveTheImage{
    for (NSUInteger i = 0; i < [views count]; i++) {
        image = [views objectAtIndex:i];
        X = [[XArray objectAtIndex:i] floatValue];
        Y = [[YArray objectAtIndex:i] floatValue];
        image.center=CGPointMake(image.center.x + X, image.center.y + Y);

        if (CGRectIntersectsRect(image.frame,centre.frame)) {
           // If the object is in collision, we add it to our set
           // If it was already in it, it does nothing
           [collisionObjects addObject:image];
        }
        else {
           // If the object is not in collision we remove it, 
           // just in case it was in collision last time.
           // If it was not, it does nothing.
           [collisionObjects removeObject:image];
        }
    }

    // The intersectFlag is updated : YES if the set is empty, NO otherwise.
    intersectFlag = [collisionObjects count] > 0;
    // We display the count of objects in collision
    label.text= [NSString stringWithFormat:@"%d", [collisionObjects count]];
}

通过这种方式,您始终可以使用[collisionObjects count]计算碰撞对象的数量。

相关问题