Yad Smood
Yad Smood

Reputation: 2942

Three.js camera rotation issue

I want to rotate the camera around the x-axis on the y-z plane while looking at the (0, 0, 0) point. It turns out the lookAt function behaves weird. When after rotating 180°, the geometry jump to another side unexpectedly. Could you please explain why this happens, and how to avoid it?

You can see the live demo on jsFiddle: http://jsfiddle.net/ysmood/dryEa/

class Stage
    constructor: ->
        window.requestAnimationFrame = 
            window.requestAnimationFrame or
            window.webkitRequestAnimationFrame or
            window.mozRequestAnimationFrame

        @init_scene()
        @make_meshes()

    init_scene: ->
        @scene = new THREE.Scene

        # Renderer
        width = window.innerWidth;
        height = window.innerHeight;
        @renderer = new THREE.WebGLRenderer({
            canvas: document.querySelector('.scene')
        })
        @renderer.setSize(width, height)

        # Camera
        @camera = new THREE.PerspectiveCamera(
            45,                 # fov
            width / height,     # aspect
            1,                  # near
            1000                # far
        )
        @scene.add(@camera)

    make_meshes: ->
        size = 20
        num = 1

        geo = new THREE.CylinderGeometry(0, size, size)
        material = new THREE.MeshNormalMaterial()
        mesh = new THREE.Mesh(geo, material)
        mesh.rotation.z = Math.PI / 2

        @scene.add(mesh)

    draw: =>
        angle = Date.now() * 0.001
        radius = 100

        @camera.position.set(
            0,
            radius * Math.cos(angle),
            radius * Math.sin(angle)
        )
        @camera.lookAt(new THREE.Vector3())

        @renderer.render(@scene, @camera)
        requestAnimationFrame(@draw)

stage = new Stage
stage.draw()

Upvotes: 0

Views: 3058

Answers (1)

WestLangley
WestLangley

Reputation: 104843

You are rotating the camera around the X-axis in the Y-Z plane. When the camera passes over the "north" and "south" poles, it flips so as to stay right-side-up. The camera's up-vector is (0, 1, 0) by default.

Set the camera x-position to 100 so, and its behavior will appear correct to you. Add some axes to your demo for a frame of reference.

This is not a fault of the library. Have a look at the Camera.lookAt() source code.

If you want to set the camera orientation via its quaternion instead, you can do that.

three.js r.59

Upvotes: 3

Related Questions