How to programmatically wrap png texture around cube in SceneKit

浪子不回头ぞ 提交于 2019-12-07 11:50:39

问题


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


回答1:


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




回答2:


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'



来源:https://stackoverflow.com/questions/28386009/how-to-programmatically-wrap-png-texture-around-cube-in-scenekit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!