Spawning a Spritekit node at a random time

2019-03-22 03:25发布

问题:

I'm making a game where I have a node that is spawning and falling from the top of the screen. However I want to make the nodes spawn at random time intervals between a period of 3 seconds. So one spawns in 1 second, the next in 2.4 seconds, the next in 1.7 seconds, and so forth forever. I am struggling with what the code should be for this.

Code I currently have for spawning node:

    let wait = SKAction.waitForDuration(3, withRange: 2)
    let spawn = SKAction.runBlock { addTears()
    }

    let sequence = SKAction.sequence([wait, spawn])
    self.runAction(SKAction.repeatActionForever(spawn))

The code for my addTears() function is:

func addTears() {
        let Tears = SKSpriteNode (imageNamed: "Tear")
        Tears.position = CGPointMake(Drake1.position.x, Drake1.position.y - 2)
        Tears.zPosition = 3
        addChild(Tears)

    //gravity
    Tears.physicsBody = SKPhysicsBody (circleOfRadius: 150)
    Tears.physicsBody?.affectedByGravity = true

    //contact
    Tears.physicsBody = SKPhysicsBody (circleOfRadius: Tears.size.width/150)
    Tears.physicsBody!.categoryBitMask = contactType.Tear.rawValue
    Tears.physicsBody!.contactTestBitMask = contactType.Bucket.rawValue
    }

回答1:

It's not advisable that you use NSTimer with SpriteKit (see SpriteKit - Creating a timer). Instead, to generate random times you could use SKAction.waitForDuration:withRange:

Creates an action that idles for a randomized period of time.

When the action executes, the action waits for the specified amount of time, then ends...

Each time the action is executed, the action computes a new random value for the duration. The duration may vary in either direction by up to half of the value of the durationRange parameter...

To spawn nodes at random times you could combine waitForDuration:withRange with runBlock: together in an SKAction sequence. For example:

// I'll let you adjust the numbers correctly...
let wait = SKAction.wait(forDuration: 3, withRange: 2)
let spawn = SKAction.run {
    // Create a new node and it add to the scene...
}

let sequence = SKAction.sequence([wait, spawn])
self.run(SKAction.repeatForever(sequence))
// self in this case would probably be your SKScene subclass.