How to move sprite along CGPath at variable speed
I am programming a game and want to move a sprite along a fixed path (straight and curves - railroad engine I think), but I want to be able to control the animation in terms of the speed of the sprites - and change that speed in response to game events.
followPath: duration: is closed in SKAction, but there doesn't seem to be an option to adjust the speed on the fly - I definitely care about the speed of the sprite, not the length of the path.
CGPath seems to be the correct construct for defining the path for a sprite, but there doesn't seem to be enough functionality to grab points along the path and do my own math.
Can you suggest a suitable approach?
source to share
You can adjust the execution speed of any SKAction with the speed property. For example, if you set action.speed = 2, the action will run twice as fast.
SKAction *moveAlongPath = [SKAction followPath:path asOffset:NO orientToPath:YES duration:60];
[_character runAction:moveAlongPath withKey:@"moveAlongPath"];
Then you can adjust the character speed to
[self changeActionSpeedTo:2 onNode:_character];
How to change the speed of SKAction ...
- (void) changeActionSpeedTo:(CGFloat)speed onNode:(SKSpriteNode *)node
{
SKAction *action = [node actionForKey:@"moveAlongPath"];
if (action) {
action.speed = speed;
}
}
source to share
Try thinking like this:
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);
source to share