Reputation: 1
I am trying to use CGRectIntersectsRect to detect a collision between two CAlayers. One is part of a hierarchy of layers, and the other is a sublayer of the main view. I have tried this:
Accessing presentationLayer of an animation to detect collisions
It does not work with any consistency. Here is what I have right now. "LegLowerLeft" is part of a hierarchy of CAlayers and "rec2" is a subview of the main view. Thanks in advance for any help.:
-(void) checkForCollisionWithRec{
if(CGRectIntersectsRect(((CALayer*)self.creature.legLowerLeft.presentationLayer).frame,
((CALayer*)rec2.presentationLayer).frame))
{ NSLog(@"Collision detected"); }
else{NSLog(@"No collision detected");}
}
Upvotes: 0
Views: 596
Reputation: 299305
The frame of a layer is in the coordinate space of its superview. If two layers have different superviews, then you cannot compare their frames directly. You must convert them to a consistent coordinate space.
CALayer *layer1 = self.creature.legLowerLeft.presentationLayer;
CALayer *layer2 = rec2.presentationLayer;
CGRect frame1 = layer1.frame;
CGRect frame2 = [layer1 convertRect:layer2.frame fromLayer:layer2];
if(CGRectIntersectsRect(frame1, frame2))
{
NSLog(@"Collision detected");
}
else
{
NSLog(@"No collision detected");
}
Upvotes: 3