I have a function that creates SpriteNode copies and move each copy along a rectangle path at a specified interval. I have a problem with this interval that the action is executed at inconsistent interval making odd gaps between sprite nodes while action is running.
var items = [SKSpriteNode]();
let item = SKSpriteNode(imageNamed: "Spaceship");
func createItem(scene: SKScene) {
let square = UIBezierPath(rect: CGRect(x: -300, y: -150, width: 700, height: 300));
let follow = SKAction.follow(square.cgPath, asOffset: false, orientToPath: false, duration: 5.0);
for i in 0..<6 {
if let itemCopy = item.copy() as? SKSpriteNode {
itemCopy.position = CGPoint(x: -300, y: -150);
items.append(itemCopy);
scene.addChild(itemCopy);
let otherWait = SKAction.wait(forDuration: 1.0, withRange: 2.0);
let otherSequence = SKAction.sequence([otherWait, SKAction.repeatForever(follow)]);
itemCopy.run(otherSequence);
}
}
}
My understanding is that I can't rely on for loop
for timing and this issue could be caused by that. Is there a way to get around this with some kind of callback function?
The problem here is not related to the for loop, but comes from that fact you're using wait(forDuration:withRange:)
, and this is the intended behaviour. The documentation states:
Creates an action that idles for a randomized period of time.
I think you're looking for the wait(forDuration:)
method and it will work just fine :)