-2

I am making a game in SpriteKit and in this game I have platforms that spawn, I want to make it so that an object such as a gem or coin has a chance of spawning on the platform when it is spawned

I need it to be random and also be able to choose what it spawns (Either a gem or a coin)

Any ideas?

4

1 回答 1

1

To use stack overflow correctly, you should always post some code. People will not help if you just want them to do the work for you.

The best way is to subclass your platforms, here is the basic idea behind it.

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

Than in your scenes you spawn the platforms like so

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

Hope this helps

于 2016-01-14T12:20:24.823 回答