Xcode SpriteKit - Removing Sprites and stopping an

2019-04-09 02:47发布

问题:

I am new to Swift and SpritKit and having a few issues with my game.

In my didMoveToView(view: SKView) { } section of my code I call the below statement which populates monsters on the screen. In my func addMonster() { } The monsters then animated to move from the right hand side, to the left hand side of the screen. Once they are off the screen the opposite side, the sprite gets removed.

CODE A

    runAction(SKAction.repeatActionForever(
        SKAction.sequence([
            SKAction.runBlock(addMonster),
            SKAction.waitForDuration(1.0),SKAction.
            ])
        ))

In the add Mons†er function, i call the following code which moves the Monster across the screen.

    let actualDuration = random(min: CGFloat(6.0), max: CGFloat(10.0))
    let actionMove = SKAction.moveTo(CGPoint(x: -monster.size.width/2, y: actualY), duration: NSTimeInterval(actualDuration))
    let actionMoveDone = SKAction.removeFromParent()
    monster.runAction(SKAction.sequence([actionMove, actionMoveDone]))

All of the code above is working fine.

When the user has killed an X amount of monsters, I want all the other monsters of the screen to disappear and stop spawning.

My questions are, how do I a) Stop CODE A from spawning monsters and b) how do I get any monsters that are on the view, the be removed?

Thanks,

Ryann

回答1:

When you run the action, use

monster.runAction(SKAction.sequence([actionMove, actionMoveDone]), withKey: "actionA")

then cancel it with

monster.removeActionForKey("actionA")