Created
October 12, 2024 12:04
-
-
Save apptects/669294cfcda1f13463768f4c4fffbee9 to your computer and use it in GitHub Desktop.
RealityKit instancing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import AppKit | |
| import RealityKit | |
| class GameViewController: NSViewController { | |
| @IBOutlet var arView: ARView! | |
| override func awakeFromNib() { | |
| // Generating the initial mesh (just so that we can extract its MeshResource.Model, which contains the actual mesh data) | |
| let mesh = MeshResource.generateBox(size: 1) | |
| // Making sure our assumption that the mesh contains a single model is true. | |
| precondition(mesh.contents.models.count == 1) | |
| // Extracting the model. | |
| let model = mesh.contents.models.map { model in | |
| model | |
| }.first! | |
| // Create a new `Contents`, this will hold the model and the instances of that model. | |
| var contents = MeshResource.Contents() | |
| // Add the model. | |
| contents.models.insert(model) | |
| // Generate this many instances. | |
| let instanceCount = 20 | |
| for index in 0..<instanceCount { | |
| // Build the transform for this instance. | |
| var transform = Transform() | |
| // Distribute the intances along the x-axis. | |
| transform.translation.x = 2 * Float(index) - Float(instanceCount) | |
| // Create the instance, referencing the model id that you want to instance, and the transform matrix of the instance. | |
| let instance = MeshResource.Instance(id: "Instance \(index)", model: model.id, at: transform.matrix) | |
| // Add the instance. | |
| contents.instances.insert(instance) | |
| } | |
| // Create an instanced mesh resource from the new contents. | |
| let instancedMesh = try! MeshResource.generate(from: contents) | |
| // Create a ModelComponent using the instanced mesh. | |
| let material = SimpleMaterial(color: .red, isMetallic: false) | |
| let modelComponent = ModelComponent(mesh: instancedMesh, materials: [material]) | |
| // Set the ModelComponent on a ModelEntity. | |
| let modelEntity = ModelEntity() | |
| modelEntity.model = modelComponent | |
| // Anchor the ModelEntity into the scene | |
| let anchorEntity = AnchorEntity() | |
| anchorEntity.position.z = -30 | |
| anchorEntity.addChild(modelEntity) | |
| arView.scene.addAnchor(anchorEntity) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment