Bret
Bret

Reputation: 912

How to programmatically wrap png texture around cube in SceneKit

I'm new to SceneKit... trying to get some basic stuff working without much success so far. For some reason when I try to apply a png texture to a CNBox I end up with nothing but blackness. Here is the simple code snippet I have in viewDidLoad:

    let sceneView = (view as SCNView)

    let scene = SCNScene()

    let boxGeometry = SCNBox(width: 10.0, height: 10.0, length: 10.0, chamferRadius: 1.0)

    let mat = SCNMaterial()
    mat.locksAmbientWithDiffuse = true
    mat.diffuse.contents = ["sofb.png","sofb.png","sofb.png","sofb.png","sofb.png", "sofb.png"]
    mat.specular.contents = UIColor.whiteColor()
    boxGeometry.firstMaterial = mat

    let boxNode = SCNNode(geometry: boxGeometry)

    scene.rootNode.addChildNode(boxNode)

    sceneView.scene = scene

    sceneView.autoenablesDefaultLighting = true
    sceneView.allowsCameraControl = true

What it ends up looking like is a white light source reflecting off of a black cube against a black background. What am I missing? I appreciate all responses

Upvotes: 3

Views: 5669

Answers (2)

Jerry Frost
Jerry Frost

Reputation: 467

If you had different images, you would build a different SCNMaterial object from each like so:

let material_L = SCNMaterial()
material_L.diffuse.contents = UIImage(named: "CapL")

Here, CapL refers to a .png file that has been stored in the project's Assets.xcassets folder. After building 6 such objects, you hand them to the boxNode as follows:

boxGeometry.materials = [material_L, material_green_r, material_K, material_purple_r, material_g, material_j]

Note that "boxGeometry" would be better named "box" or "cube". Also, it would be a good idea to do that work in a new class in your project, constructed like:

class BoxScene: SCNScene {

Which you would then call with modern Swift in your viewController's viewDidLoad method like this:

let scnView = self.view as! SCNView
scnView.scene = BoxScene()

(For that let statement to work, go to Main.storyboard -> View Controller Scene -> View Controller -> View -> Identity icon Then under Custom Class, change it from UIView to SCNView. Otherwise, you receive an error message, like:

Could not cast value of type 'UIView' to 'SCNView'

Upvotes: 4

David Rönnqvist
David Rönnqvist

Reputation: 56625

Passing an array of images (to create a cube map) is only supported by the reflective material property and the scene's background.

In your case, all the images are the same, so you would only have to assign the image (not an array) to the contents to have it appear on all sides of the box

Upvotes: 2

Related Questions