As I swipe on the screen I want a SCNNode object to rotate while the speed is decreasing. When the speed is 0 the animation should stop. Here is my code:
ViewDidLoad:
sceneView.delegate = self
let scene = SCNScene(named: "art.scnassets/Cube.dae")!
self.cubeNode = scene.rootNode.childNode(withName: "Cube", recursively: true)
self.cubeNode?.position = SCNVector3Make(0, 0, -1)
sceneView.scene = scene
let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipes(gesture:)))
swipeRight.direction = UISwipeGestureRecognizerDirection.right
self.view.addGestureRecognizer(swipeRight)
let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipes(gesture:)))
swipeLeft.direction = UISwipeGestureRecognizerDirection.left
self.view.addGestureRecognizer(swipeLeft)
The handleSwipes function:
@objc func handleSwipes(gesture: UIGestureRecognizer) {
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.right:
animateSpin(direction: .right)
case UISwipeGestureRecognizerDirection.left:
animateSpin(direction: .left)
default:
break
}
}
}
And the animateSpin function:
func animateSpin(direction: SwipeDirection) {
let spin = CABasicAnimation(keyPath: "rotation")
spin.fromValue = NSValue.init(scnVector4: SCNVector4(0, 0, 0, 0))
switch direction {
case .left:
spin.toValue = NSValue.init(scnVector4: SCNVector4(x: 0, y:-1, z:0, w: 2 * .pi))
case .right:
spin.toValue = NSValue.init(scnVector4: SCNVector4(x: 0, y:1, z:0, w: 2 * .pi))
}
spin.speed = 1
spin.repeatCount = 20
self.cubeNode!.addAnimation(spin, forKey: "spin around")
}
I also have an enum for the directions:
enum SwipeDirection {
case right
case left
}
Would really appreciate any suggestions on how to do this. Is there a way to run some code after each animation repeat?
[SOLVED]