2013-07-17 107 views
0

我想在y-z平面上围绕x轴旋转相机,同时查看(0, 0, 0)点。事实证明lookAt函数行为怪异。当旋转180°后,几何图形意外跳到另一侧。你能解释为什么发生这种情况,以及如何避免它?Three.js相机旋转问题

你可以看到的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() 
+0

您可能碰到了Gimbal Lock问题(您可以在网上搜索)。解决方法是使用四元数旋转(也可研究)。请注意,最新的Three.js,r59现在默认使用四元数,并且在Object3D中有新的旋转方法可以帮助(rotateX(),rotateAroundAxis()和朋友)。 – yaku

+0

你确定这是一个万向节锁定问题吗?问题是我不知道'lookAt'函数的机制。为什么团队不在'lookAt'函数中使用Quaternion? –

回答

1

你周围旋转在Y-Z平面X轴相机。当相机经过“北”和“南”极时,它会翻转以保持正面朝上。相机的向上矢量默认为(0, 1, 0)

将相机x位置设置为100,其行为对您而言显得正确。在您的演示中添加一些轴作为参考框架。

这不是图书馆的错。看看Camera.lookAt()源代码。

如果您想通过四元数设置相机方向,您可以这样做。

three.js r.59

+0

我阅读了源代码。谢谢,它有帮助。 three.js的文件误导了我的想法。 –

+0

我已经给出了x位置的偏移量,但同样的问题出现http://jsfiddle.net/ysmood/dryEa/ –

+0

为了帮助您了解发生了什么,请将相机偏移量设置为200,然后是50,然后是20。一切正常,因为它应该 - 相机避免被颠倒旋转。如果您不在乎相机是否倒置,请使用“TrackballControls”来控制相机。 http://threejs.org/examples/misc_controls_trackball.html – WestLangley