我在viewDidAppear中有一个动画,如下所示
-(void)viewDidAppear:(BOOL)animated
{
for (int i = 0; i < 100; i++) {
p = arc4random_uniform(320)%4+1; //global integer
CGRect startFrame = CGRectMake(p*50, -50, 50, 50);
CGRect endFrame = CGRectMake(p*50, CGRectGetHeight(self.view.bounds) + 50,
50,
50);
animatedView = [[UIView alloc] initWithFrame:startFrame];
animatedView.backgroundColor = [UIColor redColor];
[self.view addSubview:animatedView];
[UIView animateWithDuration:2.f
delay:i * 0.5f
options:UIViewAnimationCurveLinear
animations:^{
animatedView.frame = endFrame;
} completion:^(BOOL finished) {
[animatedView removeFromSuperview];
}];
}
}
它只是从屏幕顶部创建小方块并移动到底部。 我还有一个UIImageView,它由x轴上的加速度计控制。目的不是触及动画对象。就像一场简单的比赛。但是我无法找到如何检测imageView和动画之间的碰撞?
答案 0 :(得分:5)
首先,您需要将所有动画视图对象保存在数组中,以检查与图像视图的碰撞。所以你.h文件创建一个NSArray来保存动画视图
NSMutableArray animatedViews;
然后在viewDidLoad中初始化它
animatedViews = [[NSMutableArray alloc] init];
然后更改代码viewWillAppear并添加一行
[self.view addSubview:animatedView];
[animatedViews addObject:animatedView];
然后创建一个检查碰撞的函数,它需要一个参数用于计划的计时器
-(void) checkCollision: (NSTimer *) theTimer{
for(int i = 0; i < [animatedViews count]; i++) {
UIView *theView = [animatedViews objectAtIndex:index];
if (CGRectIntersectsRect(theView.frame, yourImageView.frame) {
// the image collided
// stop the timer and do your work here
}
}
}
然后在viewWillAppear中添加此行来安排定时器每隔半秒调用一次以调用函数来检查碰撞
[NSTimer scheduledTimerWithTimeInterval: 0.5
target: self
selector: @selector(checkCollision:)
userInfo: nil
repeats: YES];
答案 1 :(得分:3)
问题在于此测试:if (CGRectIntersectsRect(theView.frame, yourImageView.frame)
你必须检查视图的presentationLayer:
CGRect movingFrame = [[theImage.layer presentationLayer] frame];
if (CGRectIntersectsRect(movingFrame, panier.frame)) {
// the image collided
}