1

我在 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 和动画之间的碰撞?

4

2 回答 2

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];
于 2012-08-24T08:15:48.333 回答
3

问题出在这个测试中:if (CGRectIntersectsRect(theView.frame, yourImageView.frame) 您必须检查视图的presentationLayer:

CGRect movingFrame = [[theImage.layer presentationLayer] frame];
    if (CGRectIntersectsRect(movingFrame, panier.frame)) {           
        // the image collided            
    }
于 2012-10-11T21:03:19.737 回答