Choosing random image for SKSpriteNode

点点圈 提交于 2019-12-06 04:26:32

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()

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