Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotate a node using pan gesture in SceneKit iOS

I am using the below code to rotate a node using the pan gesture. I like to rotate my node only in the y-axis.

let translation = gestureRecognize.translation(in: gestureRecognize.view!)

let x = Float(translation.x)
let y = Float(-translation.y)
let anglePan = (sqrt(pow(x,2)+pow(y,2)))*(Float)(Double.pi)/180.0

var rotationVector = SCNVector4()
rotationVector.x = 0.0
rotationVector.y = x
rotationVector.z = 0.0
rotationVector.w = anglePan


node.rotation = rotationVector

if(gestureRecognize.state == UIGestureRecognizerState.ended) {
    let currentPivot = node.pivot
    let changePivot = SCNMatrix4Invert( node.transform)

    node.pivot = SCNMatrix4Mult(changePivot, currentPivot)
    node.transform = SCNMatrix4Identity

}

This works for nodes with Euler set to (x: 0, y: 0, z: 0). But my node has Euler (x: -90, y: 0, z: 0). For my Euler values above code rotates the object in the wrong angle. How can I rotate a node with my/different Euler values?

like image 639
prabhu Avatar asked Jun 27 '17 13:06

prabhu


1 Answers

I think you might be overcomplicating what you need to do here.

In my example, I have created an SCNNode with an SCNBox Geometry and set it's Euler Angles as per your example: (x: -90, y: 0, z: 0).

The 1st thing you need to do, is create a variable to store the rotationAngle around the YAxis:

var currentAngleY: Float = 0.0

Then try this function in order to rotate your node around the YAxis (which works fine by the way):

 /// 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 }

        print(nodeToRotate.eulerAngles)
}

Hope it helps...

like image 178
BlackMirrorz Avatar answered Nov 11 '22 06:11

BlackMirrorz