Using Scenekit UIViewRepresentable (code block 1 bellow), we could add a tap gesture recognizer hit test like
With the new SceneView for Scenekit/SwiftUI (code block 2), we add a tap gesture recognizer?
I found this API, but its not clear how to use it...
https://developer.apple.com/documentation/scenekit/sceneview/3607839-ontapgesture
import SwiftUI
import SceneKit
import UIKit
import QuartzCore
struct SceneView: UIViewRepresentable {
func makeUIView(context: Context) -> SCNView {
let view = SCNView(frame: .zero)
let scene = SCNScene(named: "ship")!
view.allowsCameraControl = true
view.scene = scene
// add a tap gesture recognizer
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
	view.addGestureRecognizer(tapGesture)
return view
}
func handleTap(_ gestureRecognize: UIGestureRecognizer) {
// retrieve the SCNView
let view = SCNView(frame: .zero)
// check what nodes are tapped
let p = gestureRecognize.location(in: view)
let hitResults = view.hitTest(p, options: [:])
// check that we clicked on at least one object
if hitResults.count > 0 {
// retrieved the first clicked object
let result = hitResults[0]
// get material for selected geometry element
let material = result.node.geometry!.materials[(result.geometryIndex)]
// highlight it
SCNTransaction.begin()
SCNTransaction.animationDuration = 0.5
// on completion - unhighlight
SCNTransaction.completionBlock = {
SCNTransaction.begin()
SCNTransaction.animationDuration = 0.5
material.emission.contents = UIColor.black
SCNTransaction.commit()
}
material.emission.contents = UIColor.green
SCNTransaction.commit()
}
}
func updateUIView(_ view: SCNView, context: Context) {
}
}
import SwiftUI
import SceneKit
struct ContentView: View {
var scene = SCNScene(named: "ship.scn")
var cameraNode: SCNNode? {
scene?.rootNode.childNode(withName: "camera", recursively: false)
}
var body: some View {
SceneView(
scene: scene,
pointOfView: cameraNode,
options: []
)
.allowsHitTesting(/*@START_MENU_TOKEN@*/true/*@END_MENU_TOKEN@*/)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
5
0
6.3k