SpriteKit,Swift 2.0 - 在游戏地图上生成一个对象

SpriteKit, Swift 2.0 - Making an object spawn on the game map

我正在用 SpriteKit 制作游戏,在这个游戏中我有生成的平台,我想制作它以便 gem 或硬币等对象有机会在平台上生成时它已生成

我需要它是随机的并且能够选择它产生的东西(gem 或硬币)

有什么想法吗?

要正确使用堆栈溢出,您应该总是post一些代码。如果您只是想让他们为您完成工作,人们是不会提供帮助的。

最好的方法是对平台进行子类化,这是其背后的基本思想。

 enum PlatformObject: Int {
     case Gem = 0
     case Coin
 }

 class Platform: SKSpriteNode {

     init (size: CGSize, color: SKColor, objectType: PlatformObject, spawnObjectRandomly: Bool) { // create your own init for your needs
         super.init (texture: nil, color: color, size: size)

         // set up platform properties

         // Than spawn object
         if spawnObjectRandomly {
               spawnRandomObject()
         } else if objectType == .Coin {
               spawnCoin()
         } else if objectType == .Gem {
               spawnGem()
         }
    }

    required init?(coder aDecoder: NSCoder) {
         fatalError("init(coder:) has not been implemented")
    }

    func spawnRandomObject() {
       let randomNumber = Int(arc4random() % 2)  // 0 and 1
       if randomNumber == 0 {
          // spawn gem
          spawnGem()
       } else {
          // spawn coin
          spawnCoin()
       }
   }

   func spawnCoin() {
       let coin = SKSpriteNode(...
   }

   func spawnGem() {
       let gem = SKSpriteNode(...
   }
}

比起在你的场景中你像这样生成平台

  class GameScene: SKScene {
      let size = // set your size
      let color = // set color

      let platform1 = Platform(size: size, color: color, objectType: .Gem, spawnObjectRandomly: false) 
      ...
      // if false will spawn selected objectType ("Gem" in this example)


      let platform2 = Platform(size: size, color: color, objectType: .Gem, spawnObjectRandomly: true) 
     // if true will spawn random object regardless of objectType settings
      ...
 }

希望对您有所帮助