Hello,
You can hitTest your scene to determine the nearest entity that was hit (assuming this entity has an adequate collision shape), for example:
class GameViewController: NSViewController {
@IBOutlet var arView: ARView!
override func awakeFromNib() {
let boxMesh = MeshResource.generateBox(size: 0.1)
let anchor = AnchorEntity()
anchor.name = "Anchor"
// Creates a hierarchy of 10 boxes.
var previousEntity: Entity = anchor
for index in 1...10 {
let model = ModelEntity(mesh: boxMesh)
model.name = String("Box \(index)")
model.transform.translation = .init(0.2, 0, 0)
previousEntity.addChild(model)
previousEntity = model
}
anchor.generateCollisionShapes(recursive: true)
// Adds the hierarchy to the scene.
arView.scene.addAnchor(anchor)
arView.addGestureRecognizer(NSClickGestureRecognizer(target: self, action: #selector(clicked(_:))))
}
@objc
func clicked(_ sender: NSClickGestureRecognizer) {
// Hit-tests the scene at the provided view location, returning only the closest hit collision shape.
let results = arView.hitTest(sender.location(in: arView), query: .nearest)
guard let firstHitEntity = results.first?.entity else { return }
// Logs the name of the hit entity.
print(firstHitEntity.name)
}
}