Problem with the counter of collisions
Here is my code :
-(void)detectCollision{
imageView.cente开发者_如何转开发r = 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 ?
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;
}
}
}
to find out collision u should use with bounds not frame
bounds - size inside of object
frame - offset from superview x,y + size(bounds)
here i assume u are in portrait mode
-(void)detectCollision{
if(CGRectContainsPoint( imageView.bounds, CGPointMake(160, 240)) ){
label.text= [NSString stringWithFormat:@"%d", count];
++count;
}
}
精彩评论