我希望能够根据分数关闭和打开我的SKEmitterNode(雨颗粒)。但是我的更新函数被不断调用,即我最终在屏幕上显示数百万个粒子,下面是我当前的代码...我如何构建我的代码,以便只有达到分数才能调用雨粒子一次?
class GameScene: SKScene, SKPhysicsContactDelegate {
func setUpRain() {
if let rainParticle = SKEmitterNode(fileNamed: "Rain") {
rainParticle.position = CGPointMake(frame.size.width, frame.size.height)
rainParticle.name = "rainParticle"
rainParticle.zPosition = Layer.Flash.rawValue
worldNode.addChild(rainParticle)
}
}
func makeItRain() {
let startRaining = SKAction.runBlock {
self.setUpRain()
}
runAction(startRaining, withKey: "Rain")
}
func stopRaining() {
removeActionForKey("Rain")
worldNode.enumerateChildNodesWithName("rainParticle", usingBlock: { node, stop in
node.removeFromParent()
})
}
}
class PlayingState: GKState {
unowned let scene: GameScene //used to gain access to our scene
override func updateWithDeltaTime(seconds: NSTimeInterval) {
scene.updateForegroundAndBackground()
scene.updateScore()
if scene.score > 2 {
scene.makeItRain()
}
if scene.score > 4 {
scene.stopRaining()
}
}
答案 0 :(得分:2)
有几种方法可以做到这一点,但最简单的方法是每次切换只调用一次makeItRain()或stopRaining()。我的意思是,一旦调用了makeItRain,在调用stopRaining之前不能再调用它。这可以使用类似的布尔值来完成:
var rainToggle: Bool = false; //True = Raining
override func updateWithDeltaTime(seconds: NSTimeInterval) {
scene.updateForegroundAndBackground()
scene.updateScore()
if (scene.score > 4){
scene.stopRaining()
rainToggle = false;
}
else if (scene.score > 2 && !rainToggle) {
scene.makeItRain()
rainToggle = true;
}
}
这只是效率稍低,因为你无缘无故地每帧都调用stopRaining(),但它完成了工作并且易于理解。另请注意,我必须翻转if语句的顺序(否则它将无法工作)。