Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find whether two objects intersect each other?

I used the following code to create and animate the object

//For creating two imageview 
UIImageView *bbl1Obj=[[UIImageView alloc]initWithFrame:CGRectMake(34,77,70, 70)];
bbl1Obj.image=[UIImage imageNamed:@"bubble1.png"];
[self.view addSubview:bbl1Obj];
UIImageView *bbl2Obj=[[UIImageView alloc]initWithFrame:CGRectMake(224,77,70, 70)];
bbl2Obj.image=[UIImage imageNamed:@"bubble2.png"];
[self.view addSubview:bbl2Obj];
// for animating the objects
[UIImageView beginAnimations:nil context:NULL];
[UIImageView setAnimationDuration:3];
[bbl1Obj setFrame:CGRectMake(224,77,70, 70)];
[UIImageView commitAnimations];

[UIImageView beginAnimations:nil context:NULL];
[UIImageView setAnimationDuration:3];
[bbl2Obj setFrame:CGRectMake(34,77,70, 70)];
[UIImageView commitAnimations];

I want to display an image when the two image intersect each other. but i don't know how to find whether the images intersect other or not while animating. Can anyone please tell me how to find whether two images intersect each other or not while animating.

Thanks in advance

like image 688
surendher Avatar asked Jul 25 '12 04:07

surendher


2 Answers

This is what I would normally use to test for intersections. However, I'm not sure if it would work mid-animation.

if(CGRectIntersectsRect(bbl1Obj.frame, bbl2Obj.frame)) {

    //They are intersecting
}

It that didn't work for testing for intersections while currently animating, try using the presentationLayer property of the view's layer. Here's what the presentationLayer is, taken from the CALayer Class Reference:

presentationLayer

Returns a copy of the layer containing all properties as they were at the start of the current transaction, with any active animations applied.

With that in mind, you can try this now:

CALayer *bbl1ObjPresentationLayer = (CALayer*)[bb1Obj.layer presentationLayer];
CALayer *bbl2ObjPresentationLayer = (CALayer*)[bb2Obj.layer presentationLayer];

if(CGRectIntersectsRect(bbl1ObjPresentationLayer.frame, bbl2ObjPresentationLayer.frame)) {

    //They are intersecting
}

So if the first way doesn't work, the second way surely will.

like image 157
pasawaya Avatar answered Dec 03 '22 07:12

pasawaya


Use CGRectContainsPoint which gives the objects intersect.

    if(CGRectContainsPoint([bbl1Obj bounds], CGPointMake(bbl2Obj.frame.origin.x, bbl2Obj.frame.origin.y)))
    {
NSLog(@"intersect");
    }
like image 35
Nims Avatar answered Dec 03 '22 07:12

Nims