开发者

How to move a ball horizontally with CABasicAnimation and stop the ball at the correct place

开发者 https://www.devze.com 2023-01-26 19:14 出处:网络
I\'m trying to write a game and I\'m a bit stuck with this animation. I have a ball that is animating horizontally in my screen. Here is the code:

I'm trying to write a game and I'm a bit stuck with this animation. I have a ball that is animating horizontally in my screen. Here is the code:

CABasicAnimation *horizontalBallAnimation = [CABasicAnimation animationWithKeyPath:@"position"];
[horizontalBallAnimation setFromValue:[NSValue valueWithCGPoint:CGPointMake(50.0, 300.0 )]];
[horizontalBallAnimation setToValue:[NSValue valueWithCGPoint:CGPointMake(220.0, 300.0 )]];

horizontalBallAnimation.delegate = self;
horizontalBallAnimation.repeatCount = 1e100f;
//horizontalBallAnimation.autoreverses = YES;
horizontalBallAnimation.duration = 2.0;

[gameBallLayer addAnimation:horizontalBallAnimation forKey:@"horizontalBallAnimation"];

This is works great. However my problem is that when I stop the animation - just by tapping on the screen - the ball before going to the right positi开发者_如何学Goon;

[gameLogic ballGameObject].x = [[[gameBallLayer presentationLayer] valueForKeyPath:@"position.x"] doubleValue];
    [gameLogic ballGameObject].y = [[[gameBallLayer presentationLayer] valueForKeyPath:@"position.y"] doubleValue];

first animates to the "ToValue" of the horizontalBallAnimation. Then, it goes to the correct value set by the gameObject. Someone can please help me with this?


What you need to do is set the target position within aCATransactionthat disables actions. For example:

//--------------------------------------------------------------------------------------------------

#pragma mark - CAAnimation Delegate Methods 

//--------------------------------------------------------------------------------------------------

- (void)animationDidStart:(CAAnimation *)theAnimation
{
    [CATransaction begin];
    [CATransaction setValue:(id)kCFBooleanTrue
                     forKey:kCATransactionDisableActions];

    // Set the layer's target position here.        

    [CATransaction commit];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号