Reputation: 131
I have two objects: one that is moving by animation, and another that is moving when I drag it around with my finger. I want to be able to detect when the two "collide" using CGIntersectsRect. However, I've heard that in order to do this with animations, I need to access the presentation layer to grab values from there. I have no idea how to go about doing this, however. This is the animation code I have:
UIImage *flakeImage = [UIImage imageNamed:@"apple.png"];
UIImageView *flakeView = [[UIImageView alloc] initWithImage:flakeImage];
flakeView.frame = CGRectMake(200, -25.0, 25.0, 25.0);
[self.view addSubview:flakeView];
[UIView beginAnimations:nil context:(flakeView)];
[UIView setAnimationDuration:2];
flakeView.frame = CGRectMake(200, 800.0, 25.0, 25.0); ]
and here is the code for the object I move with my finger:
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
// get current touch location
UITouch *touch = [[event touchesForView:self.view] anyObject];
CGPoint point = [touch locationInView:self.view];
// update location of the image
basketView.center = CGPointMake(point.x, basketView.center.y);
}
How can I access the presentationLayer of the flakeView animation so that I can detect when the two objects intersect?
Upvotes: 3
Views: 1533
Reputation: 8855
You simply need to keep around a reference to both of your views. Then all you have to do is:
if(CGRectIntersectsRect(((CALayer*)basketView.layer.presentationLayer).frame,
((CALayer*)flakeView.layer.presentationLayer).frame)) {
//handle the collision
}
Upvotes: 2