首页 文章

在 ARkit 中旋转对象

提问于
浏览
-1

我的场景中有一个物体,当我将手指移过屏幕时,我希望物体朝那个方向旋转。这是屏幕上的一个杯子,我的手指在屏幕上滑动应该围绕中心点旋转立方体,但不要移动杯子的位置。它只应在主动滑动时旋转

1 回答

  • 4

    旋转SCNNode是一项相当简单的任务。

    您应该首先创建一个变量来将 rotationAngle 存储在 YAxis 周围或您希望在 e.g 上执行旋转的任何其他变量:

    var currentAngleY: Float = 0.0
    

    您还需要有一些方法来检测要旋转的节点,在本例中我们将调用 currentNode e.g.

    var currentNode: SCNNode!
    

    在这个例子中,我将围绕 YAxis 旋转。

    如果你想使用UIPanGestureRecognizer,你可以这样做:

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

    或者,如果你想使用UIRotationGesture,你可以这样做:

    /// Rotates An SCNNode Around It's YAxis
    ///
    /// - Parameter gesture: UIRotationGestureRecognizer
    @objc func rotateNode(_ gesture: UIRotationGestureRecognizer){
    
    //1. Get The Current Rotation From The Gesture
    let rotation = Float(gesture.rotation)
    
    //2. If The Gesture State Has Changed Set The Nodes EulerAngles.y
    if gesture.state == .changed{
    
        currentNode.eulerAngles.y = currentAngleY + rotation
    }
    
    //3. If The Gesture Has Ended Store The Last Angle Of The Cube
    if(gesture.state == .ended) {
        currentAngleY = currentNode.eulerAngles.y
    
     }
    }
    

    希望能帮助到你...

相关问题