Rotate scnnode with velocity

Asked by At

I have an scnnode that I rotate with a UIPanGestureRecognizer around it's Y axis. This is great, but I'd like to apply inertia to the avatar so it keeps spinning (and slows down) once the user lifts their finger, kinda like what you have with a scrollView. Is this possible?

   func addMoveAvatarGestures(sceneView: SCNView) {
        let pan = gestureWithRootNode(target:self, action:#selector(rotateAvatar(_:)))
        if let scene = sceneView.scene {
            pan.rootNode = scene.rootNode
        }
        pan.maximumNumberOfTouches = 1
        pan.minimumNumberOfTouches = 1
        pan.delegate = self
        self.rotationGesture = pan
        sceneView.addGestureRecognizer(pan)
    }

    @objc func rotateAvatar(_ sender: gestureWithRootNode) {

        guard let nodeToRotate = sender.rootNode else {
            return
        }


        let translation = sender.translation(in: sender.view!)
        let xToAngle = Float(self.view.frame.width) / Float(360)
        let newAngleY = Float(translation.x) * xToAngle
        let velocity = sender.velocity(in: sender.view!)
        if (fabs(velocity.x) > fabs(velocity.y)) {
            sender.setTranslation(CGPoint.zero, in: sender.view!)
            nodeToRotate.eulerAngles.y += nodeExtensions.deg2rad(newAngleY)
        }
    }

1 Answers

0
MasDennis On

You can use applyTorque for this which changes the node's angular momentum.

It affects the node's angularVelocity. You can constrain or restrict this effect by setting the angularVelocityFactor.