Dav*_*son 2 scenekit swift scnnode
我如何返回用于设置 SCNNode 的球体几何(SCNSphere)的半径。我想在我移动一些与父节点相关的子节点的方法中使用半径。下面的代码失败了,因为结果节点似乎不知道半径,我不应该将节点传递给方法吗?
我的数组索引也失败了,说 Int 不是一个范围。
我想建立的东西,从这个
import UIKit
import SceneKit
class PrimitivesScene: SCNScene {
override init() {
super.init()
self.addSpheres();
}
func addSpheres() {
let sphereGeometry = SCNSphere(radius: 1.0)
sphereGeometry.firstMaterial?.diffuse.contents = UIColor.redColor()
let sphereNode = SCNNode(geometry: sphereGeometry)
self.rootNode.addChildNode(sphereNode)
let secondSphereGeometry = SCNSphere(radius: 0.5)
secondSphereGeometry.firstMaterial?.diffuse.contents = UIColor.greenColor()
let secondSphereNode = SCNNode(geometry: secondSphereGeometry)
secondSphereNode.position = SCNVector3(x: 0, y: 1.25, z: 0.0)
self.rootNode.addChildNode(secondSphereNode)
self.attachChildrenWithAngle(sphereNode, children:[secondSphereNode, sphereNode], angle:20)
}
func attachChildrenWithAngle(parent: SCNNode, children:[SCNNode], angle:Int) {
let parentRadius = parent.geometry.radius //This fails cause geometry does not know radius.
for var index = 0; index < 3; ++index{
children[index].position=SCNVector3(x:Float(index),y:parentRadius+children[index].radius/2, z:0);// fails saying int is not convertible to range.
}
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Run Code Online (Sandbox Code Playgroud)
问题radius在于parent.geometry返回 aSCNGeometry而不是SCNSphere。如果您需要获取radius,则需要先强制转换parent.geometry为SCNSphere。为了安全起见,最好使用一些可选的绑定和链接来做到这一点:
if let parentRadius = (parent.geometry as? SCNSphere)?.radius {
// use parentRadius here
}
Run Code Online (Sandbox Code Playgroud)
在访问节点radius上的时,您还需要这样做children。如果你把所有这些放在一起并稍微清理一下,你会得到这样的东西:
func attachChildrenWithAngle(parent: SCNNode, children:[SCNNode], angle:Int) {
if let parentRadius = (parent.geometry as? SCNSphere)?.radius {
for var index = 0; index < 3; ++index{
let child = children[index]
if let childRadius = (child.geometry as? SCNSphere)?.radius {
let radius = parentRadius + childRadius / 2.0
child.position = SCNVector3(x:CGFloat(index), y:radius, z:0.0);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,您正在attachChildrenWithAngle使用 2 个孩子的数组进行调用:
self.attachChildrenWithAngle(sphereNode, children:[secondSphereNode, sphereNode], angle:20)
Run Code Online (Sandbox Code Playgroud)
如果你这样做,你将for在访问第三个元素时在该循环中遇到运行时崩溃。每次调用该函数时,您要么需要传递一个包含 3 个子项的数组,要么更改该for循环中的逻辑。