Choosing random image for SKSpriteNode

坚强是说给别人听的谎言 提交于 2019-12-07 21:49:03

问题


I am trying to build a simple obstacle jumping app. I want the image for the obstacle to be picked randomly from a set of images. I have tried using a combination of the arc4random_uniform function and switch case but that doesn't seem to update the SKSpriteNode. What am i doing wrong?

class PlayScene: SKScene, SKPhysicsContactDelegate{
      ...
      var block3 = SKSpriteNode(imageNamed: "lion")
      ....
}


override func update(currentTime: NSTimeInterval) {
     .....
     blockRunner()
    }


func blockRunner() {

        var imageNamedAnimal = ""
        var randomIndex = arc4random_uniform(2)
        switch(randomIndex) {
        case 0 : imageNamedAnimal = "turtle"
        case 1: imageNamedAnimal = "lion"
        default: imageNamedAnimal = "turtle"
        }

        block3 = SKSpriteNode(imageNamed: imageNamedAnimal)
        .....
        }   

At what point should i try to set the random image? Block3 seems to pick the lion image always which i had sent at the beginning of the code despite the fact that imageNamedAnimal shows random values in each frame.


回答1:


You can avoid loading the images each time you change the character by creating and storing the images as textures. Here's an example of how to do that:

Create an array to store the textures

var textures = [SKTexture]()

In didMoveToView, create and store the textures

textures.append(SKTexture(imageNamed: "turtle"))
textures.append(SKTexture(imageNamed: "lion"))
textures.append(SKTexture(imageNamed: "rhino"))
...

In the blockRunner method, add the following

 // Randomly select a character
 let rand = Int(arc4random_uniform(UInt32(textures.count)))
 let texture = textures[rand] as SKTexture

 block3.texture = texture
 // Optionally, resize the sprite
 block3.size = texture.size()



回答2:


You are creating a new SKSpriteNode when you call the initializer, but you never add it to the view. Instead, you can change the image in the sprite by setting its texture, like this:

block3.texture = SKTexture(imageNamed: imageNamedAnimal)


来源:https://stackoverflow.com/questions/27605491/choosing-random-image-for-skspritenode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!