How to find whether two objects intersect each other?

后端 未结 2 1507
不知归路
不知归路 2021-01-04 21:22

I used the following code to create and animate the object

//For creating two imageview 
UIImageView *bbl1Obj=[[UIImageView alloc]initWithFrame:CGRectMake(34         


        
相关标签:
2条回答
  • 2021-01-04 21:50

    Use CGRectContainsPoint which gives the objects intersect.

        if(CGRectContainsPoint([bbl1Obj bounds], CGPointMake(bbl2Obj.frame.origin.x, bbl2Obj.frame.origin.y)))
        {
    NSLog(@"intersect");
        }
    
    0 讨论(0)
  • 2021-01-04 22:07

    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.

    0 讨论(0)
提交回复
热议问题