Spritkit node spawns at random times

I am making a game where I have a node that spawns and falls from the top of the screen. However, I want the nodes to appear at a random interval of time between a period of 3 seconds. So once every 1 second, next 2.4 seconds, next 1.7 seconds, etc. Forever and ever. I am struggling that there must be code for this.

The code I'm currently using to spawn node:

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

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

      

Code for my addTears () function:

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
    }

      

+3


source to share


1 answer


Not recommended for use NSTimer

with SpriteKit (see SpriteKit - creating a timer ). Instead, to generate random times, you can useSKAction.waitForDuration:withRange:

Creates an activity that is idle for a randomized amount of time.

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

Each time the action is executed, the action calculates a new random value for the duration. The duration can vary in any direction by up to half the value of durationRange ...



To create nodes in a random order, you can combine waitForDuration:withRange

with runBlock:

together in sequence SKAction

. For example:

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

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

      

+3


source







All Articles