Reputation: 903
How can I set up background animations only once and make them move forever?
I'm developing a game using iOS Swift and SpriteKit. I have a lot of background nodes in my game, like clouds, mountains, etc.
Currently I'm moving clouds around the scene like this. This code is in the override func update
:
if self.cloud01.position.x < 0 - self.cloud01.size.width {
self.cloud01.position.x = self.frame.size.width + (self.cloud01.size.width / 2)
} else {
self.cloud01.position.x -= 0.5
}
Whenever the cloud moves out of the scene (left side) it will be reset to the right side and move again.
I want to take all these if-statements out of the update function and set them up only once. I've tried this:
//This is in my didMoveToView
runAction(SKAction.repeatActionForever(SKAction.runBlock(backgroundAnimations)))
//It calls this function
func backgroundAnimations() {
if self.cloud01.position.x < 0 - self.cloud01.size.width {
self.cloud01.position.x = self.frame.size.width + (self.cloud01.size.width / 2)
} else {
self.cloud01.position.x -= 0.5
}
}
How can I set up background animations only once and make them move forever?
Thanks!
Upvotes: 2
Views: 69
Reputation: 974
You can use SKAction
s. Simply add this line when you initialize your clouds.
world
- your clouds parentNode
(probably you need to replace with self
)
runAction(SKAction.repeatActionForever(SKAction.sequence([
SKAction.moveByX(-world.frame.size.width , y: 0, duration: 10.0),
SKAction.moveByX(world.frame.size.width , y: 0, duration: 0),
])))
Upvotes: 3