I am trying to read a .obj file into a SCNNode from the local drive on a macOS app (not iOS) with the following code:
let url = NSURL(string: objPath!)
let asset = MDLAsset(url: url! as URL)
let node = SCNNode(mdlObject: asset.object(at: 0))
node.geometry?.firstMaterial?.diffuse.contents = NSColor.red
scnView.scene?.rootNode.addChildNode(node)
The objPath is correct and absolute path to a local folder (not inside app build). But it's giving "Could not open OBJ file" error while reading. I need to access local path only.
This should let you load an obj/dae file in swift/xcode 10.2+:
Create a scenekit model catalog by going to File --> New --> File and selecting "SceneKit Catalog" from the list.
import SceneKit.ModelIO
Then:
guard let url = Bundle.main.url(forResource: "your_obj_filename", withExtension: "obj", subdirectory: "your_folder.scnassets")
else { fatalError("Failed to find model file.") }
let asset = MDLAsset(url:url)
guard let object = asset.object(at: 0) as? MDLMesh
else { fatalError("Failed to get mesh from asset.") }
let newNode = SCNNode(mdlObject: object)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With