简体   繁体   中英

Rotating SCNNode on Y Axis Based on Pan Gesture

I have a model which I rotate using the pan gesture. It works fine but it does not rotate all 360 degrees. It rotates to 180 and then stops. Also if I end the pan gesture and starts again then the position is reset. Here is my code.

 @objc func panned(recognizer :UIPanGestureRecognizer) {

        var newAngleY :Float = 0.0

        if recognizer.state == .changed {

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

            print(translation.x)

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

            if let hitTestResult = scnHitTestResults.first {

                let chairNode = hitTestResult.node

                newAngleY = (Float)(translation.x)*(Float)(Double.pi)/180
                newAngleY += chairNode.eulerAngles.y/180
                chairNode.eulerAngles.y = newAngleY
            }
        }

        else if recognizer.state == .ended {
            currentAngleY = newAngleY
        }

    }

You could try this:

Create a var currentAngleY: Float = 0.0

Then in your PanGestureRecognizer try the following:

/// Rotates An Object On It's YAxis
///
/// - Parameter gesture: UIPanGestureRecognizer
@objc func rotateObject(gesture: UIPanGestureRecognizer) {

    guard let nodeToRotate = currentNode else { return }

    let translation = gesture.translation(in: gesture.view!)
    var newAngleY = (Float)(translation.x)*(Float)(Double.pi)/180.0
    newAngleY += currentAngleY

    nodeToRotate.eulerAngles.y = newAngleY

    if(gesture.state == .ended) { currentAngleY = newAngleY }
}

nodeToRotate refers to an SCNNode I have already selected, but you should be able to adapt it as you see fit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM