繁体   English   中英

iPhone编程:UIImageView和动画的碰撞检测

[英]iphone programming: collision detection of a UIImageView and an animation

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

首先,您需要将所有动画视图对象保存在一个数组中,以检查与图像视图的冲突。 因此,在您的.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];

问题是在此测试中: if (CGRectIntersectsRect(theView.frame, yourImageView.frame) ,则必须检查视图的presentationLayer:

CGRect movingFrame = [[theImage.layer presentationLayer] frame];
    if (CGRectIntersectsRect(movingFrame, panier.frame)) {           
        // the image collided            
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM