1

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.
inexcitus
  • 2,471
  • 2
  • 26
  • 41

1 Answers1

1

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

Alok Subedi
  • 1,601
  • 14
  • 26