Programmatically setting texture in Scene generated by Reality Composer

余生长醉 提交于 2019-12-07 17:28:33

You forgot to set a boxComponent which need to be stored on the entity.

For this use set() instance method.

In your code it should look like this:

anchor.cylinder!.components.set(cylinderModelComponent)

In my code it looks like this:

anchor.steelBox!.components.set(boxComponent)

Here are my full code version (I tested it in macOS app):

import AppKit
import RealityKit

class GameViewController: NSViewController {

    @IBOutlet var arView: ARView!

    override func awakeFromNib() {

        let anchor = try! Experience.loadBox()
        anchor.steelBox?.scale = SIMD3(x: 9, y: 9, z: 9)
        anchor.steelBox?.orientation = simd_quatf(angle: -Float.pi/4,
                                                   axis: SIMD3(x: 1, y: 1, z: 0))      

        let boxEntity: Entity = anchor.steelBox!.children[0]
        var boxComponent: ModelComponent = boxEntity.components[ModelComponent].self!

        let paths: NSArray = NSSearchPathForDirectoriesInDomains(.documentDirectory, 
                                                                 .userDomainMask, 
                                                                  true) as NSArray

        // If you're testing it in macOS app – place your Image.png here:
        // /Users/<UserName>/Library/Containers/<ApplicationName>/Data/Documents/

        let path: NSString = paths.object(at: 0) as! NSString
        let filePath: NSString = path.strings(byAppendingPaths: ["Image.png"])[0] as NSString
        let url = URL(fileURLWithPath: filePath as String)

        var material = SimpleMaterial()
        material.tintColor = NSColor.yellow
        material.baseColor = try! MaterialColorParameter.texture(TextureResource.load(contentsOf: url))
        material.roughness = MaterialScalarParameter(floatLiteral: 0.1)
        material.metallic = MaterialScalarParameter(floatLiteral: 0.1)    
        boxComponent.materials = [material]

        anchor.steelBox!.components.set(boxComponent)
        arView.scene.anchors.append(anchor)
    }
}

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