Reputation: 317
i'm using two UIImageViews, i have added to each UIImageView a subview (UIView). I use the CGRectIntersectsRect to detect collision, but doesn't work. So I have:
This is the first UIImageView
hand = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 13.5, 176)];
[hand setImage:[UIImage imageNamed:@"hand0.png"]];
[hand setContentMode:UIViewContentModeScaleAspectFit];
/// Add SUBVIEW which needs to be detected for collision
hView = [[UIView alloc]initWithFrame:CGRectMake(3, 12, 7, 10)];
[hView setBackgroundColor:[UIColor redColor]];
[hand addSubview:hView];
[hand bringSubviewToFront:hView];
hand.center = self.view.center;
[self.view addSubview:hand];
And here is the second UIImageView
ball = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 33.5, 176)];
[ball setImage:[UIImage imageNamed:@"ball0.png"]];
[ball setContentMode:UIViewContentModeScaleAspectFit];
/// Add SUBVIEW to detect for collision
bView = [[UIView alloc]initWithFrame:CGRectMake(3, 155, 28, 10)];
[bView setBackgroundColor:[UIColor greenColor]];
[ball addSubview:bView];
[ball bringSubviewToFront:bView];
ball.center = self.view.center;
[self.view addSubview:ball];
And here is my code for collision detection, which runs every second.
- (void)checkCollision
{
if (CGRectIntersectsRect(bView.frame, hView.frame)) {
//do something here
}
}
Any ideas why it doesn't detect the collision? The only thing i have in mind is because the hView and bView are subviews of the UIImageView.
Upvotes: 0
Views: 126
Reputation: 318934
The problem is that the frames of bView
and hView
are relative to their respective superviews. You need to convert their frames to a common ancestor so they can be compared properly. The view controller's view would be a good candidate.
- (void)checkCollision {
CGRect hFrame = [hView convertRect:hView.bounds toView:self.view];
CGRect bFrame = [bView convertRect:bView.bounds toView:self.view];
if (CGRectIntersectsRect(bFrame, hFrame)) {
//do something here
}
}
Upvotes: 1