如何沿着具有可变速度的CGPath移动精灵

时间:2014-08-02 11:41:49

标签: ios sprite-kit

我正在编写游戏并希望沿固定路径移动精灵(直道和曲线 - 想想铁路引擎)但我希望能够根据精灵速度驱动动画 - 并改变响应速度游戏活动。

followPath:duration:在SKAction中很接近,但似乎没有办法调整速度"在飞行中" - 我非常关心精灵速度 - 不是'持续时间遵循路径'。

CGPath似乎是用于定义精灵路径的正确构造,但似乎没有足够的功能来抓住路径上的点并进行自己的数学运算。

有人能提出合适的方法吗?

2 个答案:

答案 0 :(得分:5)

您可以使用其speed属性调整任何SKAction的执行速度。例如,如果设置action.speed = 2,则操作将以两倍的速度运行。

SKAction *moveAlongPath = [SKAction followPath:path asOffset:NO orientToPath:YES duration:60];
[_character runAction:moveAlongPath withKey:@"moveAlongPath"];

然后您可以通过

调整角色的速度
[self changeActionSpeedTo:2 onNode:_character];

改变SKAction速度的方法......

- (void) changeActionSpeedTo:(CGFloat)speed onNode:(SKSpriteNode *)node
{
    SKAction *action = [node actionForKey:@"moveAlongPath"];
    if (action) {
      action.speed = speed;
    }
}

答案 1 :(得分:1)

尝试这样的事情:

CGMutablePathRef cgpath = CGPathCreateMutable();

//random values
float xStart = [self getRandomNumberBetween:0+enemy.size.width to:screenRect.size.width-enemy.size.width ];
float xEnd = [self getRandomNumberBetween:0+enemy.size.width to:screenRect.size.width-enemy.size.width ];

//ControlPoint1
float cp1X = [self getRandomNumberBetween:0+enemy.size.width to:screenRect.size.width-enemy.size.width ];
float cp1Y = [self getRandomNumberBetween:0+enemy.size.width to:screenRect.size.width-enemy.size.height ];

//ControlPoint2
float cp2X = [self getRandomNumberBetween:0+enemy.size.width to:screenRect.size.width-enemy.size.width ];
float cp2Y = [self getRandomNumberBetween:0 to:cp1Y];

CGPoint s = CGPointMake(xStart, 1024.0);
CGPoint e = CGPointMake(xEnd, -100.0);
CGPoint cp1 = CGPointMake(cp1X, cp1Y);
CGPoint cp2 = CGPointMake(cp2X, cp2Y);
CGPathMoveToPoint(cgpath,NULL, s.x, s.y);
CGPathAddCurveToPoint(cgpath, NULL, cp1.x, cp1.y, cp2.x, cp2.y, e.x, e.y);

SKAction *planeDestroy = [SKAction followPath:cgpath asOffset:NO orientToPath:YES duration:5];
[self addChild:enemy];

SKAction *remove2 = [SKAction removeFromParent];
[enemy runAction:[SKAction sequence:@[planeDestroy,remove2]]];

CGPathRelease(cgpath);