我正在使用以下代码为我的游戏中的玩家生成随机图像。
var playerTexture = [SKTexture]()
playerTexture.append(SKTexture(imageNamed: “red”))
playerTexture.append(SKTexture(imageNamed: “blue”))
playerTexture.append(SKTexture(imageNamed: “green”))
let rand = Int(arc4random_uniform(UInt32(playerTexture.count)))
let chosenColor = playerTexture[rand] as SKTexture
let playerSkin = chosenColor
上面的代码生成一个名为playerSkin的随机SKTexture(红色,蓝色或绿色)。
player = SKSpriteNode(texture: playerSkin)
player.size = CGSize(width: 50, height: 50)
player.position = location
self.addChild(player)
player.name = chosenColor.description
然后,此代码的下一部分将播放器创建为SKSpriteNode,并为其分配红色,蓝色或绿色的随机纹理。但是主要的事情是代码使用以下命令将player.name分配给随机选择的图像:
player.name = chosenColor.description
然后,我使用打印检查播放器的名称。
print(player.name)
但是,当我检查播放器的名称时,根据选择的随机图像,它会显示为以下内容之一:
可选(“ \'red \'(120 x 120)”)
可选(“ \'blue \'(120 x 120)”)
可选(“ \'绿色\'(120 x 120)”)
我的图像称为“红色”,“蓝色”和“绿色”,位于Xcode的Assets.xcassets文件夹中。
我的图像是120 x 120,但是为什么会出现这些长随机名称?如何设置“红色”,“蓝色”或“绿色”作为播放器的名称?
我需要将名称准确地命名为“红色”,“蓝色”或“绿色”,因为我想稍后使用player.name来实现其他功能。
也许有更好的方法,但这是我想到的第一件事-使playerTexture变量成为一个元组数组,其中包含纹理和您要为其指定的名称:
var playerTexture = [(SKTexture, String)]()
playerTexture.append((SKTexture(imageNamed: “red”), "red"))
playerTexture.append((SKTexture(imageNamed: “blue”), "blue"))
playerTexture.append((SKTexture(imageNamed: “green”), "green"))
let rand = Int(arc4random_uniform(UInt32(playerTexture.count)))
let chosenColor = playerTexture[rand].0 as SKTexture
let colorName = playerTexture[rand].1
let playerSkin = chosenColor
player = SKSpriteNode(texture: playerSkin)
player.size = CGSize(width: 50, height: 50)
player.position = location
self.addChild(player)
player.name = colorName
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句