为SKSpriteNode选择随机图像

为SKSpriteNode选择随机图像

本文介绍了为SKSpriteNode选择随机图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个简单的障碍跳跃应用程序。我希望从一组图像中随机挑选障碍物的图像。我试过使用arc4random_uniform函数和switch case的组合,但似乎没有更新SKSpriteNode。我做错了什么?

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

我应该在什么时候尝试设置随机图像? Block3似乎总是挑选我在代码开头发送的狮子图像,尽管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.

推荐答案

通过创建和存储图像作为纹理,每次更改角色时都可以避免加载图像。以下是如何执行此操作的示例:

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

didMoveToView ,创建和存储纹理

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

blockRunner 方法中,添加以下内容

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

这篇关于为SKSpriteNode选择随机图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 17:01