I created a SCNView
and want to use a UITapGestureRecognizer to move SCNNode
‘s around the view; however, the code I implemented doesn’t seem to be working. The nodes move sometimes, but they never move to the correct spot. Does anyone know what I am doing wrong here?
@objc func handleTapGesture(_ gesture: UITapGestureRecognizer) {
let location = gesture.location(in: scnView)
guard let result = self.scnView?.hitTest(location, options: nil).first else { return }
let transform = result.simdModelTransform
let newPosition = SCNVector3(transform.columns.3.x, node.position.y, transform.columns.3.z)
node.position = newPosition
}
2
Answers
Looks like you are confused about usage of hitTest in SCNView. Firstly, note that hitTest(_:options:) will search for objects/nodes in the given scene corresponding to the ray-cast hits from point of touch. This explains why sometimes your code doesn’t work because the hit test results will be empty in case the objects are not found.
To make things work as expected, you must project the point from CGPoint into scene using following code which also requires you to provide depth.
then use the output to set the node position
You can also try using PanGesture as well.
Let me give you sample code for the same.