Alec Firtulescu
Alec Firtulescu

Reputation: 553

Move a specific node in SceneKit using touch

I have a scene with multiple nodes. I want to select a node by tapping it (if I tap nothing I want nothing to happen) and make him follow my finger only on XY axis (I know position on Z axis). Is there any method that converts location in view to SceneKit coords?

After few researches I found this and it's exactly what I want, but I don't get the code. Can somebody explain me or help me figure how can I solve my problem? https://www.youtube.com/watch?v=xn9Bt2PFp0g

Upvotes: 5

Views: 3527

Answers (2)

user3151675
user3151675

Reputation: 58149

This is Alec Firtulescu's answer as an extension for watchOS (convert it to iOS by changing WKInterfaceSCNScene to SCNView):

extension CGPoint {
    func scnVector3Value(view: WKInterfaceSCNScene, depth: Float) -> SCNVector3 {
        let projectedOrigin = view.projectPoint(SCNVector3(0, 0, depth))

        return view.unprojectPoint(SCNVector3(Float(x), Float(y), projectedOrigin.z))
    }
}

Upvotes: 1

Alec Firtulescu
Alec Firtulescu

Reputation: 553

func CGPointToSCNVector3(view: SCNView, depth: Float, point: CGPoint) -> SCNVector3 {
    let projectedOrigin = view.projectPoint(SCNVector3Make(0, 0, depth))
    let locationWithz   = SCNVector3Make(Float(point.x), Float(point.y), projectedOrigin.z)
    return view.unprojectPoint(locationWithz)
}

Looks like was pretty simple, I've made a function that gets 3 parameters. View is the SCNView where scene is attached to, depth is the z value of node, and point is a CGPoint that represents projection of 3D scene on screen.

Upvotes: 5

Related Questions