锁定相机旋转 [英] Lock camera rotation around

查看:48
本文介绍了锁定相机旋转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个使用 SceneKit 的应用程序.模型位于固定位置,用户可以围绕场景平移和旋转相机.

I am creating an app that uses SceneKit. The model is at a fixed location and the user can translate and rotate the camera around the scene.

平移工作正常,旋转相机也工作 - 只要只旋转一个轴.当相机朝下或朝上并且向左或向右旋转时,它不仅会围绕该轴旋转,还会围绕第二个轴旋转,这看起来很奇怪.

Translating works fine, and rotating the camera also works - as long as only one axis was rotated. When the camera faces down or up and the camera is rotated to the left or right, it not only rotates around that axis, but also around a second axis which looks really weird.

我尝试移动枢轴点,但没有帮助.

I tried moving the pivot point, but that didn't help.

这是我用来旋转和移动相机的代码:

Here is the code that I use for rotating and moving the camera:

fileprivate func translateCamera(_ x: Float, _ y: Float)
{
    if let cameraNode = self.cameraNode
    {
        let moveX = x * 2 // TODO Settings.speed
        let moveY = -y * 2 // TODO Settings.speed

        let position = SCNVector3Make(moveX, 0, moveY)
        let rotatedPosition = self.position(position, cameraNode.rotation)
        let translated = SCNMatrix4Translate(cameraNode.transform, rotatedPosition.x, rotatedPosition.y, rotatedPosition.z)

        cameraNode.transform = translated

        if cameraNode.position.y < 25
        {
            cameraNode.position.y = 25
        }
    }
}

fileprivate func position(_ position: SCNVector3, _ rotation: SCNVector4) -> SCNVector3
{
    if rotation.w == 0
    {
        return position
    }

    let gPosition: GLKVector3 = SCNVector3ToGLKVector3(position)
    let gRotation = GLKMatrix4MakeRotation(rotation.w, rotation.x, rotation.y, rotation.z)
    let r = GLKMatrix4MultiplyVector3(gRotation, gPosition)

    return SCNVector3FromGLKVector3(r)
}

fileprivate func rotateCamera(_ x: Float, _ y: Float)
{
    if let cameraNode = self.cameraNode
    {
        let moveX = x / 50.0
        let moveY = y / 50.0

        let rotated = SCNMatrix4Rotate(SCNMatrix4Identity, -moveX, 0, 1, 0)
        cameraNode.transform = SCNMatrix4Mult(rotated, cameraNode.transform)

        let rotated2 = SCNMatrix4Rotate(SCNMatrix4Identity, moveY, 1, 0, 0)
        cameraNode.transform = SCNMatrix4Mult(rotated2, cameraNode.transform)
    }
}

锁定"相机使其仅围绕所需轴移动的正确方法是什么?我制作了一个展示行为的小视频:

What would be the correct approach to "lock" the camera so it only moves around the desired axis? I made a small video showing the behavior:

https://www.youtube.com/watch?v=ctK-hnw7JxY

  • 只要只旋转了一个轴,它就可以正常工作.
  • 但是一旦第二个轴旋转,它也会向一侧倾斜.

推荐答案

创建空节点并添加 cameraNode 作为其子节点.为 x 旋转 cameraNode,为 y 旋转 emptyNode.

Create empty node and add cameraNode as its child. rotate cameraNode for x and emptyNode for y.

这篇关于锁定相机旋转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆