Can I use SKScene for material on an Obj file loaded in SceneKit?

128 Views Asked by At

My goal is to be able to tap on a specific model and color the surface. I have managed to do this with generic SCNSphere, SCNBox, etc.

I set it up like this, and it basically works for SCNSphere, etc:

let node = SCNNode(geometry: geometry)

let material = SCNMaterial()
        
material.specular.contents = SKColor.init(white: 0.1, alpha: 1)
material.shininess = 2.0;
        
material.normal.contents = "wood-normal.png"
        
let skScene = SKScene.init(size: CGSize(width: SPRITE_SIZE, height: SPRITE_SIZE))
skScene.backgroundColor = SKColor.orange
skScene.scaleMode = .aspectFill
material.diffuse.contents = skScene
    
geometry.firstMaterial = material

scnScene.rootNode.addChildNode(node)

enter image description here

However, when I load a .obj file and try to set the material with a SKScene I don't get anything. Here is how I set up the obj

let bundle = Bundle.main
let path = bundle.path(forResource: name, ofType: "obj")
let url = NSURL(fileURLWithPath: path!)
let asset = MDLAsset(url: url as URL)
        
guard let object = asset.object(at: 0) as? MDLMesh else {
    print("Failed to get mesh from obj asset")
    return
}

let material = SCNMaterial()
material.specular.contents = SKColor.init(white: 0.1, alpha: 1)

let skScene = SKScene.init(size: CGSize(width: SPRITE_SIZE, height: SPRITE_SIZE))
skScene.backgroundColor = SKColor.orange
skScene.scaleMode = .aspectFill
material.diffuse.contents = skScene

let geometry = SCNGeometry.init(mdlMesh: object)
let node = SCNNode(geometry: geometry)
node.geometry?.materials = [material]

scnScene.rootNode.addChildNode(node)

But as you can see, the color of the teapot is not orange

enter image description here

My question is, am I doing something wrong in terms of using a SKScene as a material for an obj file, or is there some limitation that I'm aware of? I've spent a few hours on this, and am open to suggestions if anyone has any ideas.

Also, in this sort of situation, how do I decide what the size of the SKScene is since I want to arbitrarily wrap the whole mesh with a SKScene?

Update 1 I sort of figured something out. My obj file doesn't have texture coordinates, only vertices. When I tried another obj file with texture coordinates, then the skScene seems to have loaded correctly. So I guess my teapot doesn't have uv coordinates, so it can't map the texture. Is there a way to add uv coordinates if the obj file doesn't have them already?

0

There are 0 best solutions below