1

Making a class in SceneKit is important. However, I cannot get it to work.

Here is my class code

import UIKit
import SceneKit

class Ship: SCNNode {
    override init(){
        super.init()

    let box = SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0)

    let node = SCNNode(geometry: box)

}

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


  }
}

And here is my code in the ViewController (I am using ARKit)

   let tempShip = Ship()
    tempShip.position = SCNVector3(0.1,0.1,0.1)

    sceneView.scene.rootNode.addChildNode(tempShip)

I think I am missing something basic.

paralaxbison
  • 189
  • 1
  • 2
  • 13

3 Answers3

1

You probably have not created an SCNScene and added it to your view. At least there's no sign of that in the code you posted. You need to have something like

sceneView.scene = SCNScene()

or create it using one of SCNScene's init methods.

Then you'll have a scene you can hang your node on. Don't forget to add lighting and camera.

Also: don't subclass SCNNode. Use an extension instead. If you subclass SCNNode or SCNScene you can't use the Xcode Scene Editor. See SceneKit editor set custom class for node.

Hal Mueller
  • 7,019
  • 2
  • 24
  • 42
1

You should be seeing a warning that your node variable is not being used, you need to set the geometry on the node. Change your init method to this:

override init(){
    super.init()
    let box = SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0)
    self.geometry = box
}
James P
  • 4,786
  • 2
  • 35
  • 52
0

An SCNView's scene property is an optional. Change the last line to:

guard let scene = sceneView.scene else { return }
scene.rootNode.addChildNode(tempShip)
variiance
  • 25
  • 1
  • 4