2015-04-22 47 views
0

我想知道如果有人能告訴我如何製作它,以便我可以產生隨機圖像導彈。現在我正在使用一個名爲「流星」的圖像,我還想再展示一些圖像並隨機化。我知道我需要把它們放在一個數組中,並隨機創建一個弧。我已經完成了它的聲音,但我不知道如何爲圖像做到這一點。這是我的代碼到目前爲止。在sprite kit swift中隨機化數組中的圖像。

var lastMissileAdded : NSTimeInterval = 0.0 
let missileVelocity : CGFloat = 4.0 

func addMissile() { 
    // Initializing missile node 
    var missile = SKSpriteNode(imageNamed: "meteor") 
    missile.setScale(0.44) 

    // Adding SpriteKit physics body for collision detection 
    missile.physicsBody = SKPhysicsBody(rectangleOfSize: missile.size) 
    missile.physicsBody?.categoryBitMask = UInt32(obstacleCategory) 
    missile.physicsBody?.dynamic = true 
    missile.physicsBody?.contactTestBitMask = UInt32(shipCategory) 
    missile.physicsBody?.collisionBitMask = 0 
    missile.physicsBody?.usesPreciseCollisionDetection = true 
    missile.name = "missile" 

    // Selecting random y position for missile 
    var random : CGFloat = CGFloat(arc4random_uniform(300)) 
    missile.position = CGPointMake(self.frame.size.width + 20, random - 20) 
    self.addChild(missile) 
} 

func moveObstacle() { 
    self.enumerateChildNodesWithName("missile", usingBlock: { (node, stop) -> Void in 
     if let obstacle = node as? SKSpriteNode { 
      obstacle.position = CGPoint(x: obstacle.position.x - self.missileVelocity, y: obstacle.position.y) 
      if obstacle.position.x < 0 { 
       obstacle.removeFromParent() 
      } 
     } 

    }) 
} 

回答

1

所有你需要做的是他們的名字meteor0,meteor1和meteor2和使用字符串插值與您的隨機圖像創建節點:

var missile = SKSpriteNode(imageNamed: "meteor\(arc4random_uniform(3))")