有人可以解释 why/how 这个示例场景工具包代码有效吗?

Could someone explain why/how this sample scene kit code works?

我正在使用场景工具包并尝试制作第一人称游戏。我找到了这个示例代码,用于制作带有平移手势的第一人称相机。一切正常,但我不明白这里发生了什么。有人可以解释发生了什么吗?

    func lookGestureRecognized(gesture: UIPanGestureRecognizer) {

    //get translation and convert to rotation
    let translation = gesture.translationInView(self.view)
    let hAngle = acos(Float(translation.x) / 200) - Float(M_PI_2)
    let vAngle = acos(Float(translation.y) / 200) - Float(M_PI_2)

    //rotate hero
    heroNode.physicsBody?.applyTorque(SCNVector4(x: 0, y: 1, z: 0, w: hAngle), impulse: true)

    //tilt camera
    elevation = max(Float(-M_PI_4), min(Float(M_PI_4), elevation + vAngle))
    camNode.rotation = SCNVector4(x: 1, y: 0, z: 0, w: elevation)

    //reset translation
    gesture.setTranslation(CGPointZero, inView: self.view)
}

这是相同的代码,但有一些额外的注释:

func lookGestureRecognized(gesture: UIPanGestureRecognizer) {

    // Create Translation variable, containing the 
    // "distance" traveled by the finger since the last event
    let translation = gesture.translationInView(self.view)

    // From this distance, calculate how much the camera should move
    // 1) horizontally, 2) vertically using angles (FPS controls)
    let hAngle = acos(Float(translation.x) / 200) - Float(M_PI_2)
    let vAngle = acos(Float(translation.y) / 200) - Float(M_PI_2)

    // Apply the horizontal angle to the Hero node as a force to
    // Make it rotate accordingly (physics body use forces to move)
    heroNode.physicsBody?.applyTorque(SCNVector4(x: 0, y: 1, z: 0, w: hAngle), impulse: true)

    // Use the other angle to look up and down, clamped to ±pi/4
    elevation = max(Float(-M_PI_4), min(Float(M_PI_4), elevation + vAngle))
    // Apply the new angle to teh camera on the X axis
    camNode.rotation = SCNVector4(x: 1, y: 0, z: 0, w: elevation)

    // Set the translation to 0 to avoid accumulation 
    // the next time the event is triggered
    gesture.setTranslation(CGPointZero, inView: self.view)
}

这应该有助于理解,如果您需要有关其工作原理的更多详细信息,请告诉我!

(注意:"Distance"实际上是一个二维向量)

编辑:这里有一个更好的角度解释:

    let hAngle = acos(Float(translation.x) / 200) - Float(M_PI_2)

首先,将平移(x 上的像素距离)除以 200。这是为了减慢移动速度并(不安全地)将 x 保持在 -1 和 1 之间。

Acos 给出一个值的反余弦值。结果介于 0 到 pi 之间,并且(为简化起见)仅适用于从 -1 到 1 的 x。这是它的图表:http://www.wolframalpha.com/input/?i=acos%28x%29-pi%2F2

由于我们要正反方向移动,所以我们去掉最大值的一半(M_PI_2,也就是pi/2),让结果保持在-pi/2以内pi/2

最后,如果您将手指向一个方向移动 200 像素,您将在屏幕上看到 pi/2=90°。