SKSpriteNode不使用随机数数组

时间:2016-10-23 17:56:12

标签: swift sprite-kit arc4random

我有一个重复生成的SKSpriteNode。我创建了一个随机数生成器,并尝试将返回与不同的Sprite Image相关联。但是,它不起作用。这些数字是随机生成的,即使" 2"返回时,SKSpriteNode被绘制为" Fire Barrel 1"。

class GameScene: SKScene {

var firstObstacle = SKSpriteNode()
var player = SKSpriteNode()
var randomValue = Int()

override func didMove(to view: SKView) {

    createPlayer()

    let delay = SKAction.wait(forDuration: 3)
    let repeatingAction = SKAction.run(repeatingSequence)
    let sequence = SKAction.sequence([ delay, repeatingAction ] )
    run(SKAction.repeatForever(sequence))

}

func randomSelector() {
    let array = [0, 1, 2, 3]
    let randomValue = Int(arc4random_uniform(UInt32(array.count)))
    print(array[randomValue])
}

func createPlayer() {
    player = SKSpriteNode(imageNamed: "Player")
    player.setScale(0.4)
    player.position = CGPoint(x: -player.size.width, y: 0)
    player.zPosition = 1
    addChild(player)
}

func createObstacle() {

    if randomValue == 2 {

        firstObstacle = SKSpriteNode(imageNamed: "Fire Barrel 2")

    }

    else {

        firstObstacle = SKSpriteNode(imageNamed: "Fire Barrel 1")

    }

    firstObstacle.position = CGPoint(x: self.frame.width / 2, y: -self.frame.height / 2 + firstObstacle.size.height / 2)
    firstObstacle.zPosition = 1
    addChild(firstObstacle)
}

func repeatingSequence() {
    randomSelector()
    createObstacle()

    let moveObstacle = SKAction.moveBy(x: -self.frame.width - firstObstacle.size.width, y: 0, duration: 5)
    firstObstacle.run(moveObstacle)
}


override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

}

override func update(_ currentTime: TimeInterval) {

}
}

1 个答案:

答案 0 :(得分:3)

您的问题是

let randomValue = Int(arc4random_uniform(UInt32(array.count)))

你正在做所谓的“变量阴影”。 randomValue也存在于类实例级别,但是这里因为你使用let你已经声明了一个本地范围的版本。

self.value的实际值为Int()为0.因此为什么它是“First Barrel l”。

您使用的通用设计并不是很好。除非你有一些你需要持有randomValue的真正原因,否则你不应该把它变成一个类实例变量。而是通过参数传递它。

这看起来像是:

func randomSelector() -> Int {
    let array = [0, 1, 2, 3]
    return  Int(arc4random_uniform(UInt32(array.count)))
}

func createObstacle(type:Int) {
    if (type == 2) {
        // Type 2 stuff
    } else {
        // Other stuff
    }

    // Rest of your stuff
}

createObstacle(type: randomSelector())

虽然考虑到它的工作原理,你甚至不需要参数,你可以这样做:

func createObstacle() {
    if (randomSelector() == 2) {
        // Type 2 stuff
    } else {
        // Other stuff
    }

    // Rest of your stuff
}