[英]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.