user1861051
user1861051

Reputation: 131

Too many CGRectIntersectsRect collision counts

I have a "rain" like animation moving from the top of the screen to the bottom (several images continually dropping from the top). I also have a basket image that is controlled by finger at the bottom. I want the app to count the amount of "collisions" between any dropping image and the basket, and remove the image if they do collide.

I use two timers: One to continually drop images from the top. I put each of those images in an array. Then I have another timer that, every 0.001, checks for collisions.

I've been able to get a count every time the two objects collide, but the problem is, it's counting way too much! Each visual collision, for example, counts something like 985 collisions. What am I doing wrong in my code?: Timer:

[NSTimer scheduledTimerWithTimeInterval:(0.001) target:self selector:@selector(onCollisionCheckTimer) userInfo:nil repeats:YES];

Collision checker:

- (void)onCollisionCheckTimer{
    for (x = 0; x<100; x++){
        CALayer *layer = appleView[x].layer.presentationLayer;
        if(CGRectIntersectsRect(basketView.frame, layer.frame)) {
            collision++;
            printf("%i\n", collision);
            [appleView[x] removeFromSuperview];
        }
    }
}

the printf("%i", collision); is outputting numbers in the hundreds for every collision

Upvotes: 0

Views: 234

Answers (1)

warrenm
warrenm

Reputation: 31782

First of all, your collision test timer duration is much too short. Practically speaking, the main run loop is only going to run about 60 times per second, so you should use a duration closer to 0.016. You will never get a scheduled timer to trigger every millisecond.

Secondly, views retain their layer properties even after being removed from their superview. So what's probably happening is that even when the falling objects are removed from the superview, you're still iterating over them in the appleView collection, and their properties are such that they are still intersecting the basket view.

One way to fix this would be to check the superview property of each apple view before you check for collisions. Only if it's non-nil do you need to do the collision test.

Upvotes: 1

Related Questions