在特定时间后如何删除SKSpriteNodes

And*_*ers 1 ios sprite-kit swift

我想添加SKSpriteNodes并将它们随机地以特定的时间间隔放置在场景中。然后,我希望在特定时间后删除这些节点。

问题是删除操作无效。

我尝试在SKAction.sequence中使用removeFromParent(),但未执行代码。

在特定时间后如何删除SKSpriteNodes?

import SpriteKit

class GameScene: SKScene {

override func didMoveToView(view: SKView) {
    runAction(SKAction.repeatActionForever(
        SKAction.sequence([
            SKAction.runBlock(placeFruit),
            SKAction.waitForDuration(1.0)
            ])))
}

func placeFruit() {

    let fruit = SKSpriteNode(imageNamed: "apple")
    fruit.position = CGPoint(x: frame.size.width * random(min: 0, max: 1), y: frame.size.height * random(min: 0, max: 1))

    addChild(fruit)

    runAction(
        SKAction.sequence([
            SKAction.waitForDuration(1.0),
            SKAction.removeFromParent()
            ]))
}

override func update(currentTime: CFTimeInterval) {
}

func random() -> CGFloat {
    return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
}

func random(#min: CGFloat, max: CGFloat) -> CGFloat {
    return random() * (max - min) + min
}

}
Run Code Online (Sandbox Code Playgroud)

lch*_*amp 5

您正在self而不是fruit节点上运行序列操作。

只需像这样更改功能:

func placeFruit() {

    let fruit = SKSpriteNode(imageNamed: "apple")
    fruit.position = CGPoint(x: frame.size.width * random(min: 0, max: 1), y: frame.size.height * random(min: 0, max: 1))

    addChild(fruit)

    fruit.runAction(
        SKAction.sequence([
            SKAction.waitForDuration(1.0),
            SKAction.removeFromParent()
        ])
    )

}
Run Code Online (Sandbox Code Playgroud)