gpt4 book ai didi

iphone编程: collision detection of a UIImageView and an animation

转载 作者:行者123 更新时间:2023-12-01 17:27:01 25 4
gpt4 key购买 nike

我在 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];
}];
}
}

它只是从屏幕顶部创建小方 block 并移动到底部。
我还有一个 UIImageView,它由 x 轴上的加速度计控制。目标不是触摸动画对象。就像一个简单的赛车游戏。但是我不知道如何检测 imageView 和动画之间的碰撞?

最佳答案

首先,您需要将所有动画 View 对象保存在一个数组中,以检查与 ImageView 的冲突。所以在你的 .h 文件中创建一个 NSArray 来保存动画 View

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];

关于iphone编程: collision detection of a UIImageView and an animation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12105103/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com