2013-07-16 26 views
0

我創建了一個圓柱幾何的圓錐體。然後當我想通過lookAt函數旋轉錐體指向X軸的正方向時,它就不起作用。我的代碼有什麼問題嗎?或者這是Three.js的錯誤?Three.js,lookAt函數問題

您還可以看到我的代碼上的jsfiddle:http://jsfiddle.net/ysmood/CRdxP/

class Stage 
    constructor: -> 
     @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 
     ) 
     @camera.position.z = 200; 
     @scene.add(@camera) 

    make_meshes: -> 
     size = 20 
     @mesh = new THREE.Mesh(
      new THREE.CylinderGeometry(
       0, size, size 
      ), 
      new THREE.MeshNormalMaterial() 
     ) 
     @scene.add(@mesh) 

     # I want the mesh's tip point to right, but it doesn't work. 
     @mesh.lookAt(new THREE.Vector3(1, 0, 0)) 

    draw: => 
     @renderer.render(@scene, @camera) 

stage = new Stage 
stage.draw() 

回答

4

默認情況下所有的網格有lookAt矢量設置爲(0,0,1),並up矢量設置爲(0,1,0)。 通過將lookAt矢量設置爲(1,0,0),您幾乎可以將您的網格圍繞y軸旋轉90度。

看看這個演示:http://threejs.org/examples/misc_lookat.html

你會發現

geometry.applyMatrix(new THREE.Matrix4().makeRotationFromEuler(new THREE.Vector3(Math.PI/2, Math.PI, 0))); 

該命令修改幾何形狀以如下方式錐尖側現在沿Z軸規定,後來它使用mesh.lookAt(someVector)到重新定向網格以查看空間中的某個期望點。

希望這會有所幫助。

+0

謝謝,它真的有幫助!順便說一下,我認爲'lookAt'向量的默認值應該是'(0,0,-1)',或者相機的lookAt向量默認改爲'(0,0,-1)'? –

+0

我相信相機有默認的'(0,0,-1)'。如果此答案解決了問題,請點擊答案左邊的複選標記以接受答案。謝謝。 –

+0

有沒有辦法只改變'lookAt'向量?你的解決方案改變了幾何體的初始位置,這就是我不想要的。我知道我可以使用'lookAt'將它旋轉回'(0,1,0)',但它看起來有點骯髒。 –

3

我有這個問題與camera.up矢量我自己,所以我寫了我自己的lookAt函數,不使用向上的向量。它只是將相機指向目標位置,保持當前的滾動。

CameraUtils.lookAt = function(camera, targetPosition) { 
    var targetPos = camera.worldToLocal(targetPosition.clone()); 
    var rotationAxis = new THREE.Vector3().crossVectors(
     new THREE.Vector3(0, 0, -1), 
     targetPos 
    ).normalize(); 
    var angle = new THREE.Vector3(0, 0, -1).angleTo(
     targetPos.normalize().clone()); 

    camera.rotateOnAxis(rotationAxis, angle); 
} 

這樣稱呼它:

CameraUtils.lookAt(camera, myObject.position); 

我希望它能幫助。

+1

謝謝兄弟。這對於物體而言也很有用,而不僅僅是相機。 –