我正在使用两个UIImageViews,我已经在每个UIImageView中添加了一个子视图(UIView)。我使用CGRectIntersectsRect来检测碰撞,但不起作用。所以我有:
这是第一个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];
这是第二个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];
这是我的碰撞检测代码,它每秒运行一次。
- (void)checkCollision
{
if (CGRectIntersectsRect(bView.frame, hView.frame)) {
//do something here
}
}
为什么它没有检测到碰撞的任何想法?我唯一想到的是因为hView和bView是UIImageView的子视图。
答案 0 :(得分:1)
问题在于bView
和hView
的相对于各自的超视图。您需要将它们的帧转换为共同的祖先,以便可以正确地进行比较。视图控制器的视图将是一个很好的候选者。
- (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
}
}