我正在尝试使用循环在每个几何体上添加不同的scnMaterial(UIImage),但循环不起作用。循环始终返回最后一个图像。所以我总是在每个几何体上看到相同的最后一个图像。
class GameScene: SCNScene {
var geometry = SCNBox()
var boxnode = SCNNode()
convenience init(create: Bool) {
self.init()
let offset: Int = 10
var matCounter:Int = 1
for xIndex:Int in 0...1 {
for yIndex:Int in 0...1 {
// create a geometry copy
let geometry = SCNBox(width: 0.8 , height: 0.8, length: 0.1, chamferRadius: 0.005)
let geometry1 = SCNBox(width:2 , height: 2, length: 0.1, chamferRadius: 0.005)
let img = UIImage(named:"\(matCounter).png")
let material = SCNMaterial()
material.diffuse.contents = img
geometry1.firstMaterial = material
geometry1.firstMaterial = material
matCounter = matCounter + 1
let boxnode = SCNNode(geometry: geometry)
boxnode.position.x = Float(xIndex - offset)
boxnode.position.y = Float(yIndex - offset)
let geometry1Node = SCNNode(geometry: geometry1)
geometry1Node.position.x = Float(xIndex - 20)
geometry1Node.position.y = Float(yIndex - 20)
self.rootNode.addChildNode(boxnode)
self.rootNode.addChildNode(geometry1Node)
}
}
}
以下是我得到的结果:
答案 0 :(得分:1)
根据您的评论:
我只想要六种不同材质的几何
并假设你是
你可以这样做:
override init()
{
super.init()
typealias BoxDims = (width: CGFloat, height: CGFloat,
length: CGFloat, chamferRadius: CGFloat)
let box1Dim = BoxDims(CGFloat(0.8), CGFloat(0.8), CGFloat(0.10), CGFloat(0.005))
let box2Dim = BoxDims(CGFloat(0.7), CGFloat(0.7), CGFloat(0.15), CGFloat(0.006))
let box3Dim = BoxDims(CGFloat(0.9), CGFloat(0.6), CGFloat(0.12), CGFloat(0.007))
let box4Dim = BoxDims(CGFloat(1.2), CGFloat(0.9), CGFloat(0.18), CGFloat(0.003))
let box5Dim = BoxDims(CGFloat(1.0), CGFloat(1.0), CGFloat(0.11), CGFloat(0.008))
let box6Dim = BoxDims(CGFloat(1.1), CGFloat(1.1), CGFloat(0.16), CGFloat(0.009))
let allBoxDims = [box1Dim, box2Dim, box3Dim, box4Dim, box5Dim, box6Dim]
let offset: Int = 10
var boxCounter: Int = 0
for xIndex: Int in 0...2
{
for yIndex: Int in 0...1
{
// create a geometry
let boxDim = allBoxDims[boxCounter]
let geo = SCNBox(width: boxDim.width, height: boxDim.height,
length: boxDim.length,
chamferRadius: boxDim.chamferRadius)
let img = UIImage(named: "\(boxCounter + 1).png")
let material = SCNMaterial()
material.diffuse.contents = img
geo.firstMaterial = material
boxCounter = boxCounter + 1
let boxNode = SCNNode(geometry: geo)
boxNode.position.x = Float(xIndex - offset)
boxNode.position.y = Float(yIndex - offset)
self.rootNode.addChildNode(boxNode)
}
}
}
您需要将某些逻辑转换为代码,才能将材质应用于几何体。如果您没有任何规则/逻辑,那么您可以随意申请。
答案 1 :(得分:0)
for i in 1...5 {
if let img = UIImage(named: "\(i)"){
images.append(img)
let material = SCNMaterial()
material.diffuse.contents = img
geoCopy.firstMaterial = material
}
}
这将始终保留geoCopy.firstMaterial
从图像5初始化(如果存在)。