如何防止UIAnimation干扰CADisplayLink

时间:2015-01-13 22:49:00

标签: ios objective-c cgrect uianimation cadisplaylink

在我目前的项目中,有两个主要的机制。一系列不断向上移动屏幕的对象,以及按下多个按钮移动2个对象的机制。对于向上移动屏幕的一系列对象,我使用了CADisplayLink,而对于其他机制则使用UIAnimation,但是当我运行我的项目时,我注意到UIAnimation干扰了与之关联的对象的移动。只要按下按钮,CADisplayLink就会瞬间完成。我该如何纠正这个问题?

以下是我对这两种机制的代码

-(IBAction)tap{
    CGRect frame = Person.frame;
    frame.origin.x = 16;
    frame.origin.y = 37;

    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.2];

    Person.frame = frame;
    [UIView commitAnimations];
}

-(IBAction)tap1{
    CGRect frame = Person.frame;
    frame.origin.x = 241;
    frame.origin.y = 37;

    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.2];

    Person.frame = frame;
    [UIView commitAnimations];
}

-(IBAction)tapR1{
    CGRect frame = Person1.frame;
    frame.origin.x = 302;
    frame.origin.y = 37;

    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.2];

    Person1.frame = frame;
    [UIView commitAnimations];
}

-(IBAction)tapR2{
    CGRect frame = Person1.frame;
    frame.origin.x = 526;
    frame.origin.y = 37;

    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.2];

    Person1.frame = frame;
    [UIView commitAnimations];
}

-(void)GameOver{
}

-(void)Score{
    ScoreNumber = ScoreNumber + 1;
    ScoreLabel.text = [NSString stringWithFormat:@"%i", ScoreNumber];
}

-(IBAction)StartGame:(id)sender{
    StartGame.hidden = YES;
    Spike.hidden = NO;
    Spike1.hidden = NO;
    Spike2.hidden = YES;
    SpikeR.hidden = NO;
    SpikeR1.hidden = NO;
    SpikeR2.hidden = NO;
    circle.hidden = NO;
    ScoreLabel.hidden = NO;

    [self PlaceBars];
    [self PlaceBars1];

    Movement = [CADisplayLink displayLinkWithTarget:self selector:@selector(BarMoving)];
    [Movement addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
}

-(void)BarMoving{
    Spike.center = CGPointMake(Spike.center.x, Spike.center.y - 5);
    Spike1.center = CGPointMake(Spike1.center.x, Spike1.center.y - 5);
    Spike2.center = CGPointMake(Spike1.center.x, Spike1.center.y - 5);

    if (Spike2.center.y == -115) {
        [self PlaceBars];
    }

    SpikeR.center = CGPointMake(SpikeR.center.x, SpikeR.center.y - 5);
    SpikeR1.center = CGPointMake(SpikeR1.center.x, SpikeR1.center.y - 5);
    SpikeR2.center = CGPointMake(SpikeR2.center.x, SpikeR2.center.y - 5);

    if (SpikeR2.center.y == -115) {
        [self PlaceBars1];

    }
}

1 个答案:

答案 0 :(得分:0)

我认为你使用CADisplayLink来实现所有的移动机制。

但是,将移动逻辑委托给对象,而不是拥有管理所有移动的父对象。这是您将在Unity中看到的模式。

在您的情况下,当CADisplayLink更新时,循环访问您的对象并在每个对象上调用update()方法。此更新方法将该对象向上移动5个点,就像BarMoving()所做的那样,处于正常状态。在拍打状态下,它逐渐移动到[241,37]。

当用户点击对象时,将其从正常状态更改为点击状态,设置初始速度,位置算法,目标点和上面提到的update()方法将处理点击移动。