3
votes

I am trying to scale a 3D model of a chair in ARKit using SceneKit. Here is my code for the pinch gesture:

 @objc func pinched(recognizer :UIPinchGestureRecognizer) {

        var deltaScale :CGFloat = 0.0

        deltaScale = 1 - self.lastScale - recognizer.scale

        print(recognizer.scale)

        let sceneView = recognizer.view as! ARSCNView
        let touchPoint = recognizer.location(in: sceneView)

        let scnHitTestResults = self.sceneView.hitTest(touchPoint, options: nil)

        if let hitTestResult = scnHitTestResults.first {

            let chairNode = hitTestResult.node

            chairNode.scale = SCNVector3(deltaScale,deltaScale,deltaScale)
            self.lastScale = recognizer.scale

        }

    }

It does scale but for some weird reason it inverts the 3D model upside down. Any ideas why? Also although the scaling works but it is not as smooth and kinda jumps from different scale factors when used in multiple progressions using pinch to zoom.

1

1 Answers

12
votes

Here is how I scale my nodes:

/// Scales An SCNNode
///
/// - Parameter gesture: UIPinchGestureRecognizer
@objc func scaleObject(gesture: UIPinchGestureRecognizer) {

    let location = gesture.location(in: sceneView)
    let hitTestResults = sceneView.hitTest(location)
    guard let nodeToScale = hitTestResults.first?.node else {
        return
    }

    if gesture.state == .changed {

        let pinchScaleX: CGFloat = gesture.scale * CGFloat((nodeToScale.scale.x))
        let pinchScaleY: CGFloat = gesture.scale * CGFloat((nodeToScale.scale.y))
        let pinchScaleZ: CGFloat = gesture.scale * CGFloat((nodeToScale.scale.z))
        nodeToScale.scale = SCNVector3Make(Float(pinchScaleX), Float(pinchScaleY), Float(pinchScaleZ))
        gesture.scale = 1

    }
    if gesture.state == .ended { }

}

In my example current node refers to an SCNNode, although you can set this however you like.