Spawning a Spritekit node at a random time

帅比萌擦擦* 提交于 2019-11-29 15:31:12

问题


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.


来源:https://stackoverflow.com/questions/30763875/spawning-a-spritekit-node-at-a-random-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!