Reputation: 34513
Is it possible to vary the speed of an object moving because of SKAction.followPath
? For instance, let's say we use the code below to have a ball follow a rectangular path. The code will use a constant speed throughout the path. But what if we want to vary the speed of the object along the rectangle?
let goPath = SKAction.followPath(ballPath!.CGPath, duration: 2.5)
movingBall.runAction(goPath)
Is the only option to effectively have the ball follow a rectangular path built of separate lines with different speeds (as opposed to one path)?
Thanks!
Upvotes: 2
Views: 993
Reputation: 8130
two ways of accomplishing this.
FIRST WAY:
You can use SKAction.speedBy
. You'd group SKAction.speedBy with your followPath. example:
movingBall.runAction(SKAction.group([
SKAction.followPath(ballPath!.CGPath, duration: 2.5)
SKAction.speedBy(4, duration: 2.5)
]))
Now the ball is going to reach 4 times the speed over 2.5 seconds. NOTE: now we're not going to be honoring the followPath
duration. As time passes we're increasing the speed of the sprite. It's going to reach its destination in less than 2.5 seconds.
SECOND WAY:
The other way is to use a timing function. This is probably the better way to go because we have a lot more control over how fast the ball is going to move during the animation.
example:
let goPath = SKAction.followPath(ballPath!.CGPath, duration: 2.5)
goPath.timingFunction = {
t in
return powf(t, 3)
}
movingBall.runAction(goPath)
The way a timing function works is that it gives you a block that has the current elapsed time as a float. it's your job to use some kind of computation to modify the value that comes in, and then return it.
I'm just cubing whatever time comes into the function and returning it. This makes it so the ball starts off very slow, and then accelerates very quickly towards the end of the animation.
You can get really creative and use sin waves to make things bounce, etc. Just note that any returned values <0 are ignored.
Upvotes: 3
Reputation: 77641
With the followPath SKAction this isn't possible.
What you could do though is use the update method of the node to update its position manually.
This will take a bit of work to make it follow a path but you can do a lot more than is available with SKAction.
Upvotes: 1