The docs for RealityKit include the structs: OcclusionMaterial
, SimpleMaterial
, and UnlitMaterial
for adding materials to a ModelEntity
.
Alternatively you can load in a model with a material attached to it.
I want to add a custom material/texture to a ModelEntity
programmatically. How can I achieve this on the fly without adding the material to a model in Reality Composer or some other 3D software?
As you said, there are 3 types of materials in RealityKit at the moment: SimpleMaterial
, UnlitMaterial
and OcclusionMaterial
.
So you can try the following code using SimpleMaterial
class:
var material = SimpleMaterial()
material.baseColor = try! .texture(.load(named: "image.jpg"))
material.metallic = MaterialScalarParameter(floatLiteral: 0.9)
material.roughness = MaterialScalarParameter(floatLiteral: 0.1)
/*
material.baseColor = MaterialColorParameter.color(UIColor(red: 0.7,
green: 0.5,
blue: 0.2,
alpha: 1.0))
*/
At the moment there are 4 methods in RealityKit to create simple 3D primitives: generateBox()
, generateSphere()
, generatePlane()
and generateText()
.
let mesh: MeshResource = .generateBox(size: 2.5)
let component = ModelComponent(mesh: mesh, materials: [material])
print("\(component.mesh.bounds)")
print("\(component.materials.count)")
P.S. At the moment I have no opportunity to test this code in iOS 13 but I hope it's OK.
来源:https://stackoverflow.com/questions/56828648/adding-a-material-to-a-modelentity-programmatically