0

我创建了一个应用程序,其中图像从天而降,我必须用一个用户可移动的篮子在底部“捕捉”它们。我将掉落的图像和篮子图像放在 CGRectMake 帧中,并使用 CGRectIntersectsRect 来检测碰撞。但是,它并没有检测到每一次碰撞。例如,我将在视觉上“捕捉”10 个对象,这两个框架肯定相交,但它只会说我捕捉到 2 个。我做错了什么?

这是桶的代码:

  • (void)viewDidLoad { [超级 viewDidLoad];

    basketView = [[UIImageView alloc]
                  initWithImage:[UIImage imageNamed:@"bucket.png"]];
    basketView.frame = CGRectMake(130.0, 412.0, 30.0, 30.0);
    [self.view addSubview:basketView];
    

    }

这是坠落的物体和碰撞代码:

- (void)onTimer
{
    UIImageView* appleView = [[UIImageView alloc] initWithImage:appleImage];


    int applePosition = round(random() % 320); //random starting x coord
    double scale = 1 / round(random() % 100) + 1.0; //random apple size
    double speed = 1 / round(random() % 100) + 1.0; //random apple speed


    appleView.frame = CGRectMake(applePosition, -100.0, 25.0 * scale, 25.0 * scale);

    [self.view addSubview:appleView];

    [UIView beginAnimations:nil context:(__bridge void *)(appleView)];
    [UIView setAnimationDuration:3 * speed];


    appleView.frame = CGRectMake(applePosition, 500.0, 25.0 * scale, 25.0 * scale); 


    // Test for landing in bucket
    if (CGRectIntersectsRect(basketView.frame, appleView.frame)) {
        collision++;
        printf("%i\n", collision);
        [appleView removeFromSuperview];
    }
}

编辑:我把篮子做得很大,现在我收到垃圾邮件,没有苹果出现。所以我假设它只是在起点检查与苹果的交集,而不是在实际动画期间。如何让它在动画期间检查交叉点?

4

1 回答 1

1

显然,如果您的计时器函数产生新对象,则测试将在对象创建后恰好完成,因此如果该对象实际上并未在篮子中创建,您的命中测试将始终为负。

Now, you need another timer which will test for collisions every 10th of a sec or so (depending on how fast you move your objects, this could be more or less). An even better option (form the performance point of view) is to use CADisplayLink which works pretty much like a timer only it allows you to synchronise your tests to the refresh rate of the display.

于 2012-11-29T21:37:18.957 回答