首页 文章

获取用于创建SCNNode的SCNSphere的半径

提问于
浏览
1

如何返回用于设置SCNNode的球体几何体(SCNSphere)的半径 . 我想在一个方法中使用radius,我将一些子节点相对于父节点移动 . 下面的代码失败,因为如果我没有将节点传递给方法,那么结果节点的半径似乎是未知的?

我的数组索引也失败说Int不是Range .

我正在尝试从this构建一些东西

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

}

1 回答

  • 4

    radius 的问题是 parent.geometry 返回 SCNGeometry 而不是 SCNSphere . 如果你需要获得 radius ,你需要先将 parent.geometry 转换为 SCNSphere . 为了安全起见,最好使用一些可选的绑定和链接来做到这一点:

    if let parentRadius = (parent.geometry as? SCNSphere)?.radius {
        // use parentRadius here
    }
    

    访问 children 节点上的 radius 时,您还需要这样做 . 如果你把所有这些放在一起并清理一下,你会得到这样的东西:

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

    请注意,虽然您使用2个孩子的数组调用 attachChildrenWithAngle

    self.attachChildrenWithAngle(sphereNode, children:[secondSphereNode, sphereNode], angle:20)
    

    如果你这样做,那么在访问第3个元素时,你将在 for 循环中遇到运行时崩溃 . 每次调用该函数时,您都需要传递一个包含3个子节点的数组,或者更改 for 循环中的逻辑 .

相关问题