2014-09-28 45 views
1

我正在尝试在圆形路径中移动一个SKSpriteNode,暂停该动画,然后将其从停止的位置逆转。将圆形,暂停和反向的SKSpriteNode动画化?

这是我到目前为止。

CGPathRef circle = CGPathCreateWithEllipseInRect(CGRectMake(self.frame.size.width/2-75,self.frame.size.height/2-75,150,150), NULL); 
    self.circlePathActionClockwise = [SKAction followPath:circle asOffset:NO orientToPath:YES duration:5.0]; 
    self.circlePathActionClockwise = [SKAction repeatActionForever:self.circlePathActionClockwise]; 

    [self.ball runAction:self.circlePathActionClockwise]; 
    self.ball.speed = 1.0; 

这个动画在一个圆圈的球。然后,当我想暂停和后退,我尝试:

[self.ball runAction:[self.circlePathActionClockwise reversedAction]]; 
    self.ball.speed = 1.0; 

这颠倒了动画,但它并没有从上次停止的地方开始吧。相反,它认为这是一个新的动画,并从头开始。

有没有办法从self.ball的当前位置开始动作?

非常感谢!

+0

重复的 - http://stackoverflow.com/questions/24234801/following-a-cgpath-with-skaction-without-starting-from-beginning-of-cgpath - 它不会有答案upvoted,但第一个评论可能是你最好的选择。或者...您可以将自己的代码转换为循环路径,并在需要时反转方向/暂停。如果你知道如何使用cos/sin来绘制一个圆圈,那会让你在那里。 – prototypical 2014-10-16 02:31:35

回答

2

扭转被以下的圆形路径

  1. 计算在停车点的子画面的角度(见点一个和角度THETA在图中的一个子画面的方向的步骤1)
  2. 创建开始于角度THETA
  3. 新圆形路径在相反方向上运行的动作

enter image description here

图1。以下逆时针圆形路径

甲精灵下面是如何做到这一点的一个示例:

步骤1:计算基于所述子画面的当前位置的新路径的起始角度。

- (CGFloat) angleOnCircleWithPosition:(CGPoint)position andCenter:(CGPoint)center 
{ 
    CGFloat dx = position.x - center.x; 
    CGFloat dy = position.y - center.y; 

    return atan2f(dy, dx); 
} 

步骤2:创建给定中心点和半径的圆形路径。创建从指定角度开始的路径(弧度)。

- (CGPathRef) circlePathRefWithCenter:(CGPoint)center radius:(CGFloat)radius andStartingAngle:(CGFloat)startAngle 
{ 
    CGMutablePathRef circlePath = CGPathCreateMutable(); 
    CGPathAddRelativeArc(circlePath, NULL, center.x, center.y, radius, startAngle, M_PI*2); 
    CGPathCloseSubpath(circlePath); 
    return circlePath; 
} 

您需要申报以下实例变量:

BOOL clockwise; 
SKSpriteNode *sprite; 
CGFloat circleRadius; 
CGPoint circleCenter; 

第3步:当用户点击屏幕反转精灵的方向。它假定您已经创建了一个精灵并将其添加到场景中并设置了圆弧路径的半径和中心。

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    [sprite removeActionForKey:@"circle"]; 
    CGFloat angle = [self angleOnCircleWithPosition:sprite.position andCenter:circleCenter]; 
    CGPathRef path = [self circlePathRefWithCenter:circleCenter radius:circleRadius andStartingAngle:angle]; 
    SKAction *followPath = [SKAction followPath:path asOffset:NO orientToPath:YES duration:4]; 
    if (clockwise) { 
     [sprite runAction:[SKAction repeatActionForever:followPath] withKey:@"circle"]; 
    } 
    else { 
     [sprite runAction:[[SKAction repeatActionForever:followPath] reversedAction] withKey:@"circle"]; 
    } 
    // Toggle the direction 
    clockwise = !clockwise; 
}