I have a SKScene
, in which I have a timer callback (not run loop) that at each time step updates the scene by adding and/or removing SKNodes. The idea is to animate the nodes travelling down in a straight line. Below is the code in my callback.
我有一个SKScene,我有一个定时器回调(不是运行循环),在每个时间步骤通过添加和/或删除SKNodes更新场景。这个想法是为了使直线向下行进的节点动画化。下面是我的回调中的代码。
// 1. Add new nodes
let newSprite = SKSpriteNode(imageNamed: "file")
newSprite.position = (pos, pos)
spriteList.append((sprite: newSprite, position: 0))
scene.addChild(newSprite)
var removeList = [Int]()
let action = SKAction.move(to: (new, pos), duration: 5.0)
newSprite.run(action)
// 2. Update node positions
for (i,_) in spriteList.enumerated() {
spriteList[i].position += 1
if spriteList[i].position > gridLength {
removeList.append(i)
}
}
// 3. Remove old nodes
for i in removeList {
spriteList[i].sprite.removeFromParent()
spriteList.remove(at: i)
}
At the moment, each time this callback runs, the animation stutters. When the callback stops and I have no more nodes to add, the rest of the nodes in the scene animate smoothly down. Any suggestions how I can fix this? Is the problem adding the nodes, running the logic, or something else entirely?
目前,每次回调运行时,动画都会断断续续。当回调停止并且我没有更多节点要添加时,场景中的其余节点将平滑地向下动画。有什么建议我可以解决这个问题吗?是添加节点,运行逻辑还是完全不同的问题?
1 个解决方案
#1
1
I have a SKScene, in which I have a timer callback (not run loop)
我有一个SKScene,我有一个计时器回调(不是运行循环)
Don't do it
You should never use timers with SpriteKit, always stick to the run loop instead.
你永远不应该使用SpriteKit的计时器,而是始终坚持运行循环。
Actions
If you want to repeat a block of code every n
seconds just use actions
如果您想每n秒重复一段代码,只需使用操作即可
class Scene: SKScene {
override func didMove(to view: SKView) {
super.didMove(to: view)
let action = SKAction.run { [unowned self] in
// <--- put the codwe you want to repeat every 2 seconds here
}
let wait = SKAction.wait(forDuration: 2)
let sequence = SKAction.sequence([action, wait])
let repeatForever = SKAction.repeatForever(sequence)
run(repeatForever)
}
}
#1
1
I have a SKScene, in which I have a timer callback (not run loop)
我有一个SKScene,我有一个计时器回调(不是运行循环)
Don't do it
You should never use timers with SpriteKit, always stick to the run loop instead.
你永远不应该使用SpriteKit的计时器,而是始终坚持运行循环。
Actions
If you want to repeat a block of code every n
seconds just use actions
如果您想每n秒重复一段代码,只需使用操作即可
class Scene: SKScene {
override func didMove(to view: SKView) {
super.didMove(to: view)
let action = SKAction.run { [unowned self] in
// <--- put the codwe you want to repeat every 2 seconds here
}
let wait = SKAction.wait(forDuration: 2)
let sequence = SKAction.sequence([action, wait])
let repeatForever = SKAction.repeatForever(sequence)
run(repeatForever)
}
}