Search code examples
iphonexcodeuiimageviewcollision-detectioncounter

Problem with the counter of collisions


Here is my code :

-(void)detectCollision{

  imageView.center = CGPointMake(imageView.center.x + X, imageView.center.y + Y);


    if(CGRectIntersectsRect(imageView.frame,centre.frame)){


    label.text= [NSString stringWithFormat:@"%d", count];
  ++count;
}

I have a CADisplayLink(60fps) on detectCollision. I want to increment "count" of one every time "imageView" collide with "centre", but my problem is that count increment too fast, every time there is a collision it increment of near 100 or 200, I don't know why. How can I solve this ?


Solution

  • Its because everytime the frames start intersecting in,

    if(CGRectIntersectsRect(imageView.frame,centre.frame))
    

    your condition will be true until the frames separate and the count increases over 100 in the CADisplayLink

    so you can use a BOOL and set it to true when the frames first intersects. then check whether they are separate and make the BOOL back to false.

    initialize BOOL intersectFlag to false in init. I assume that the frames wont intersect initially.

    -(void)detectCollision
    { 
        imageView.center = CGPointMake(imageView.center.x + X, imageView.center.y + Y);
    
        if(!intersectFlag)
        {    
            if(CGRectIntersectsRect(imageView.frame,centre.frame))    
            {
                intersectFlag = YES;         
                label.text= [NSString stringWithFormat:@"%d", count];
                ++count;
            }
        }
        else
        {
            if(!CGRectIntersectsRect(imageView.frame,centre.frame))
            {
                intersectFlag = NO;
            }
        }
    }