Skip to content

Instantly share code, notes, and snippets.

@Matt54
Last active July 8, 2024 10:10
Show Gist options
  • Save Matt54/4ebb393d024626378e3e7cb72c1fe687 to your computer and use it in GitHub Desktop.
Save Matt54/4ebb393d024626378e3e7cb72c1fe687 to your computer and use it in GitHub Desktop.
RealityKit Material add blend mode example
import RealityKit
import SwiftUI
struct AddBlendModeView: View {
var isSphereOnTop: Bool = true
@State var rootEntity: Entity?
var body: some View {
RealityView { content in
} update: { content in
if let rootEntity {
content.add(rootEntity)
}
}
.task {
rootEntity = await AddBlendModeView.createRootEntity(isSphereOnTop: isSphereOnTop)
}
}
static func createRootEntity(isSphereOnTop: Bool = true) async -> Entity {
let sphereResource = MeshResource.generateSphere(radius: 0.3)
let sphereMaterial = await generateAddMaterial(color: .red)
let sphereModelComponent = ModelComponent(mesh: sphereResource, materials: [sphereMaterial])
let coneResource = MeshResource.generateCone(height: 1.0, radius: 0.5)
let coneMaterial = await generateAddMaterial(color: .green)
let coneModelComponent = ModelComponent(mesh: coneResource, materials: [coneMaterial])
let root = Entity()
let topEntity = Entity()
topEntity.components.set(isSphereOnTop ? sphereModelComponent : coneModelComponent)
root.addChild(topEntity)
let bottomEntity = Entity()
bottomEntity.components.set(!isSphereOnTop ? sphereModelComponent : coneModelComponent)
root.addChild(bottomEntity)
root.scale *= scalePreviewFactor
return root
}
static func generateAddMaterial(color: UIColor) async -> UnlitMaterial {
var descriptor = UnlitMaterial.Program.Descriptor()
descriptor.blendMode = .add
let prog = await UnlitMaterial.Program(descriptor: descriptor)
var material = UnlitMaterial(program: prog)
material.color = UnlitMaterial.BaseColor(tint: color)
return material
}
}
#Preview("Sphere on top") {
AddBlendModeView()
}
#Preview("Cone on top") {
AddBlendModeView(isSphereOnTop: false)
}
var isPreview: Bool {
return ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] == "1"
}
var scalePreviewFactor: Float = isPreview ? 0.3 : 1.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment