随机生成一个 Spritekit 节点 [英] Spawning a Spritekit node at a random time

查看:42
本文介绍了随机生成一个 Spritekit 节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个游戏,其中有一个节点从屏幕顶部生成并掉落.但是,我想让节点在 3 秒的时间内以随机时间间隔生成.所以一个在 1 秒内生成,下一个在 2.4 秒内生成,下一个在 1.7 秒内生成,以此类推.我正在为代码应该是什么而苦苦挣扎.

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))

我的 addTears() 函数的代码是:

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
    }

推荐答案

不建议将 NSTimer 与 SpriteKit 一起使用(请参阅 SpriteKit - 创建计时器).相反,要生成随机时间,您可以使用 SKAction.waitForDuration:withRange:

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...

每次执行动作时,动作都会计算一个新的随机数持续时间的值. 持续时间可能会在任一方向上变化最多为 durationRange 参数值的一半...

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...

要随机生成节点,您可以在 SKAction 序列中将 waitForDuration:withRangerunBlock: 组合在一起.例如:

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.

这篇关于随机生成一个 Spritekit 节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆