Creating a subclass of a SCNNode

删除回忆录丶 提交于 2019-12-13 05:55:52

问题


I'm loading a node from a .dae file with the following code:

func newNode() -> SCNNode {
var node = SCNNode()
let scene = SCNScene(named: "circle.dae")
var nodeArray = scene!.rootNode.childNodes

for childNode in nodeArray {
    node.addChildNode(childNode as! SCNNode)
    }
return node
}

I would now like to add some properties and methods to this specific node so that when I load it in a scene it gets a random color that I can then modify whenever I want. I had done something similar with a subclass of a SCNSphere (which is a geometry and not a node, though) using:

let NumberOfColors: UInt32 = 4

enum EllipsoidColor: Int, Printable {
case Red = 0, Blue, Green, White

var ellipsoidName: String {
    switch self {
    case .Red:
        return "red"
    case .Blue:
        return "blue"
    case .Green:
        return "green"
    case .White:
        return "white"
    }
}

var description: String {
    return self.ellipsoidName
}

static func random() -> EllipsoidColor {
    return EllipsoidColor(rawValue: Int(arc4random_uniform(NumberOfColors - 1)))!
    }
}


class Ellipsoid: SCNNode {

func setMaterialColor(ellipsoidColor: EllipsoidColor) {
    let color: UIColor

    switch ellipsoidColor {
    case .Red:
        color = UIColor.redColor()
    case .Blue:
        color = UIColor.blueColor()
    case .Green:
        color = UIColor.greenColor()
    case .White:
        color = UIColor.whiteColor()
    }

    self.geometry?.firstMaterial!.diffuse.contents = color
}

var color : EllipsoidColor {
    didSet {
        self.setMaterialColor(color)
    }
}

init(color: EllipsoidColor) {
    self.color = color
    super.init()
    self.setMaterialColor(color)
    }

required init(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
    }
}

How can I "link" this subclass to the node that I obtain using newNode() ? I naively thought that using something like

let ellipsoid = newNode() as! Ellipsoid

would work, but it doesn't. Thanks for your time and help.


回答1:


Well, your code cannot work.

In newNode you create a SCNNode:

func newNode() -> SCNNode {
   var node = SCNNode()
   //...
   return node
}

And later on you tell the compiler that this SCNNode is a Ellipsoid

let ellipsoid = newNode() as! Ellipsoid

But it isn't! It’s a SCNNode. Of course your program will crash.

If you want an Ellipsoid create one:

func newEllipsoid() -> Ellipsoid {
   var node = Ellipsoid()
   //...
   return node
}

(or wherever you need to create it)



来源:https://stackoverflow.com/questions/31720237/creating-a-subclass-of-a-scnnode

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!