2

在我的应用程序中,我在 viewWillAppear 中有此代码。它只是将随机对象从屏幕顶部动画到底部。问题是我需要检测碰撞,到目前为止我学到的是不可能随时检索动画的坐标。那么如何使用 NSTimer 来实现呢?还是我应该使用 NSTimer?我想不通。任何线索将不胜感激。

-(void)viewWillAppear:(BOOL)animated
{
    for (int i = 0; i < 100; i++) {

        p = arc4random_uniform(320)%4+1;

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

}
4

4 回答 4

3

我会放弃NSTimerCADisplayLink您的目标发送消息。NSTimer可能会导致动画卡顿,因为它与设备的屏幕刷新率不同步。CADisplayLink正是这样做的,让你的动画像黄油一样运行。

文档:http: //developer.apple.com/library/ios/#documentation/QuartzCore/Reference/CADisplayLink_ClassRef/Reference/Reference.html

最终,使用CADisplayLink看起来像这样:

- (id) init {
    // ...
    CADisplayLink *displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(update:)];
    [displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    // ...
}

- (void) update {
    [myView updatePositionOrSomethingElse];
}
于 2012-09-06T16:39:43.753 回答
2

您的声明:

是否不可能随时检索动画的坐标

似乎不正确你检查吗?

看起来您可以使用 CALayer 的presentationLayer属性在动画期间提取坐标信息:

CGRect movingFrame = [[yourView.layer presentationLayer] frame];

如果动画期间发生碰撞,我将使用此信息不时检查。所以我将使用计时器来检查碰撞状态而不是动画视图。

于 2012-08-27T11:37:56.367 回答
2

您可以让您的对象以小增量进行动画处理(可能是循环)。每次完成动画,您都可以获得坐标。

于 2012-08-27T09:57:52.660 回答
1

我认为您可以在 for 循环中使用 beginAnimations - commitAnimations 语法,例如。直到 10,所以在每个循环之后你可以检查碰撞

CGRect incrementedViewFrame;

for(int i = 0; i < 10; ++i)
{

      incrementedViewFrame = CGRectMake(/*calculate the coords here*/);

      if(collision)
      {
           //do stuff
      }
      else
      {
           //do an other animation cycle
          [UIView beginAnimations:nil context:NULL];
          [UIView setAnimationBeginsFromCurrentState:YES];
          [UIView setAnimationDuration:0.1f];
          [[self viewToAnimate]setFrame:incrementedViewFrame];
          [UIView commitAnimations];
      }
}

我希望这会有所帮助!

于 2012-08-27T10:03:11.967 回答