2010-11-23 4 views
0

J'essaie d'écrire un jeu et je suis un peu coincé avec cette animation. J'ai une balle qui s'anime horizontalement dans mon écran. Voici le code:Comment déplacer une balle horizontalement avec CABasicAnimation et arrêter la balle au bon endroit

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

Ceci fonctionne très bien. Cependant, mon problème est que lorsque j'arrête l'animation - juste en appuyant sur l'écran - la balle avant d'aller à la bonne position;

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

anime d'abord à la "ToValue" de l'horizontalBallAnimation. Ensuite, il va à la valeur correcte définie par gameObject. Quelqu'un peut s'il vous plaît m'aider avec ça?

+0

utilisez cocos2d? Je trouve cela beaucoup plus facile que CA. –

+0

J'aime cocos2D mais je pense que je peux le développer avec CALayers d'une manière agréable. C'est vraiment rapide, derrière il y a un dessin openGLES. – beit

Répondre

0

Ce que vous devez faire est de définir la position cible dans un CATransaction qui désactive les actions. Par exemple:

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

#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]; 
} 
Questions connexes