Lock camera rotation around

谁说我不能喝 提交于 2021-01-28 11:55:37

问题


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

  • As long as only one axis was rotated it works fine.
  • But as soon as the second axis gets rotated, it also tilts to the side.

回答1:


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



来源:https://stackoverflow.com/questions/48430524/lock-camera-rotation-around

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!