如何关注路径:顺时针方向为矩形路径?

时间:2014-08-24 10:56:22

标签: sprite-kit skaction cgpathref

我看到这个answer关于如何使用SKAction顺时针方向跟随Circle CGPathRef。

矩形路径怎么样?默认值为逆时针方式:

CGPathRef square =     CGPathCreateWithRect(CGRectMake(pathOriginX,pathOriginY,pathWidthX,pathHeightY), NULL);
SKAction *followTrack = [SKAction followPath:square asOffset:NO orientToPath:YES duration:completeOnePathDuration];

尝试更改终点但结果是一样的。

1 个答案:

答案 0 :(得分:1)

简答:反向运行动作,按照相反方向的路径

    [sprite runAction:[followTrack reversedAction]];

长答案: followPath SKAction遵循路径的构建方向。如果您希望精灵沿顺时针或逆时针方向沿矩形路径移动,则相应地构建路径。或者,您可以使用reverseAction方法跟踪与构建方向相反的路径。以下是两种方法的示例。

    BOOL clockwise = YES;
    BOOL reversedActionMethod = NO;

    CGRect rect = CGRectMake(CGRectGetWidth(self.frame)/2-50,CGRectGetHeight(self.frame)/2-50, 100, 100);
    SKAction *followTrackCW = [SKAction followPath:[self clockwiseRectanglePathWithRect:rect] asOffset:NO orientToPath:YES duration:5];
    SKAction *followTrackCCW = [SKAction followPath:[self counterClockwiseRectanglePathWithRect:rect] asOffset:NO orientToPath:YES duration:5];

    if (!reversedActionMethod) {
        if (clockwise) {
            [sprite runAction:followTrackCW];
        }
        else {
            [sprite runAction:followTrackCCW];
        }
    }
    else {
        if (clockwise) {
            [sprite runAction:[followTrackCCW reversedAction]];
        }
        else {
            [sprite runAction: followTrackCCW];
        }
    }

在场景坐标(CCW在视图坐标中)中以顺时针顺序构建矩形路径

- (CGPathRef) clockwiseRectanglePathWithRect:(CGRect)rect
{
    CGFloat x = rect.origin.x;
    CGFloat y = rect.origin.y;
    CGFloat width = rect.size.width;
    CGFloat height = rect.size.width;

    UIBezierPath* bezierPath = UIBezierPath.bezierPath;
    [bezierPath moveToPoint: CGPointMake(x, y)];
    [bezierPath addLineToPoint: CGPointMake(x, y+height)];
    [bezierPath addLineToPoint: CGPointMake(x+width, y+height)];
    [bezierPath addLineToPoint: CGPointMake(x+width, y)];
    [bezierPath closePath];
    return bezierPath.CGPath;
}

使用内置方法在场景坐标(和视图坐标中的CW)中以逆时针顺序构造矩形路径。

- (CGPathRef) counterClockwiseRectanglePathWithRect:(CGRect)rect
{
    UIBezierPath* bezierPath = [UIBezierPath bezierPathWithRect:rect];
    return bezierPath.CGPath;
}