How to programmatically wrap a png texture around a cube in SceneKit

I'm new to SceneKit ... trying to get some basic things working without much success. For some reason, when I try to apply a png texture to a CNBox, I only get black. Here is a simple piece of code that 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 

As a result, it looks like a white light source reflected from a black cube against a black background. What am I missing? I appreciate all the answers

+3
source share
2 answers

The transfer of an array of images (to create a map of cubes) is supported only by the material property reflective and the background scene.

In your case, all the images are the same, so you only need to assign the image (and not the array) to the content so that it is displayed from all sides of the window.

0
source

If you had different images, you would build another SCNMaterial object from each like this:

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

Here, CapL refers to the .png file that was saved in the Assets.xcassets folder of the project. After creating 6 such objects, you pass them to boxNode as follows:

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

Note that "boxGeometry" will be better called "box" or "cube". In addition, it would be nice to do this work in a new class in your project, built as follows:

 class BoxScene: SCNScene { 

Which you would then call using modern Swift in your viewController viewDidLoad, for example:

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

(for this, let the operator work, go to Main.storyboard β†’ View Controller Scene β†’ View Controller β†’ View β†’ Identity icon Then, in the user class, change it from UIView to SCNView. Otherwise, you will receive an error message such as:

Unable to pass value of type "UIView" to "SCNView"

+3
source

Source: https://habr.com/ru/post/1274896/


All Articles