如何旋转 SCNBox

How to rotate an SCNBox

我正在尝试旋转使用 swipe gestures 创建的 SCNBox。例如,当我向右滑动时,盒子应该在 Y-axis 中旋转 90 度,当我向左滑动时,盒子应该旋转 -90 度。为此,我一直在使用节点的 SCNAction.rotateByX 方法来执行旋转动画。现在我遇到的问题是在 Y-axis 旋转后沿 X-axisZ-axis 旋转时,反之亦然是轴的位置发生变化。

我注意到,任何在 X、Y、Z 轴上执行的旋转都会改变其他轴指向的方向。

示例:默认位置

然后在Z-axis中旋转后:

当然这会带来问题,因为现在当我 swipe left or right 我不再得到想要的效果,因为 X-axisY-axis 现在已经交换了位置。我想知道的是为什么会发生这种情况?有没有在不影响其他轴的情况下执行旋转动画的方法?

对于我对这个主题缺乏了解,我深表歉意,因为这是我第一次接触 3d 图形。

解决方案:

func swipeRight(recognizer: UITapGestureRecognizer) {
  // rotation animation
  let action = SCNAction.rotateByX(0, y: CGFloat(GLKMathDegreesToRadians(90)), z: 0, duration: 0.5)
  boxNode.runAction(action)

  //repositoning of the x,y,z axes after the rotation has been applied
  let currentPivot = boxNode.pivot
  let changePivot = SCNMatrix4Invert(boxNode.transform)
  boxNode.pivot = SCNMatrix4Mult(changePivot, currentPivot)
  boxNode.transform = SCNMatrix4Identity
}

我还没有 运行 遇到任何问题,但使用完成处理程序来确保在重新定位之前完成对 X、Y、Z 轴的任何更改可能更安全。

我遇到了同样的问题,这是我用来实现所需行为的方法:

func panGesture(sender: UIPanGestureRecognizer) {
    let translation = sender.translationInView(sender.view!)

    let pan_x = Float(translation.x)
    let pan_y = Float(-translation.y)
    let anglePan = sqrt(pow(pan_x,2)+pow(pan_y,2))*(Float)(M_PI)/180.0
    var rotVector = SCNVector4()

    rotVector.x = -pan_y
    rotVector.y = pan_x
    rotVector.z = 0
    rotVector.w = anglePan

    // apply to your model container node
    boxNode.rotation = rotVector

    if(sender.state == UIGestureRecognizerState.Ended) {
        let currentPivot = boxNode.pivot
        let changePivot = SCNMatrix4Invert(boxNode.transform)
        boxNode.pivot = SCNMatrix4Mult(changePivot, currentPivot)
        boxNode.transform = SCNMatrix4Identity
    }
}