随机生成节点

时间:2016-07-26 23:27:53

标签: swift xcode sprite-kit

我是Swift的初学者,我需要你的提示和帮助。 我有SKTextureNode纹理,我有5个坐标(位置)。

我试图了解如何在Swift中随机时间间隔随机生成5个位置之间的SKSpriteNode

例如:

let coordinate1 = CGPoint (x: my coordinates, y: my coordinates) let coordinate2 = .....

我试图在这些点上产生纹理,但我不知道如何做到这一点。我知道如何为我的节点添加动作。我希望它们在产卵后生成并落下......

1 个答案:

答案 0 :(得分:1)

class GameScene: SKScene {
    var positions: [CGPoint]! = [CGPoint]()
    var myHero: SKSpriteNode!
    override func didMoveToView(view: SKView) {
        let pos1 = CGPointMake(50,400)
        positions.append(pos1)
        let pos2 = CGPointMake(100,400)
        positions.append(pos2)
        let pos3 = CGPointMake(200,400)
        positions.append(pos3)
        let pos4 = CGPointMake(300,400)
        positions.append(pos4)
        let pos5 = CGPointMake(400,400)
        positions.append(pos5)
        //... or : positions = [pos1,pos2,pos3...]
        self.myHero = SKSpriteNode.init(color: SKColor.blueColor(), size: CGSizeMake(50,50))
        self.myHero.alpha = 0.0
        addChild(self.myHero)
        spawn(15)
    }
    func spawn(count:Int) {
        let generateRandom = SKAction.runBlock({
            let randomPosNum = randomNumber(0...self.positions.count-1)
            let randomTime = randomDouble(1.0, max: 3.0)
            print("randomPos: \(randomPosNum) exit in randomTime:\(randomTime) ")
            self.myHero.position = self.positions[randomPosNum]
            self.runAction(SKAction.waitForDuration(randomTime))
        })
        let fadeIn = SKAction.fadeInWithDuration(0.5)
        let fadeOut = SKAction.fadeOutWithDuration(0.0)
        let fall = SKAction.moveToY(-30, duration: 0.5)
        self.myHero.runAction(SKAction.repeatAction(SKAction.sequence([generateRandom,fadeIn,fall,fadeOut]), count: count))
    }
}
func randomNumber(range: Range<Int> = 1...6) -> Int {
    let min = range.startIndex
    let max = range.endIndex
    return Int(arc4random_uniform(UInt32(max - min))) + min
}
func randomDouble(min: Double, max: Double) -> Double {
    return (Double(arc4random()) / Double(UINT32_MAX)) * (max - min) + min
}

<强>输出

enter image description here