2017-01-16 202 views
1

我想將一個子對象(圓柱體)與另一個對象(cube2)對齊。我使用了lookAt函數,但對齊方式不正確。我的錯誤在哪裏?three.js lookAt函數無法正常工作

我有以下代碼:

//cube 1 
    var cube=new THREE.BoxGeometry(2,2,2); 
    var material=new THREE.MeshBasicMaterial ({ color: 0xffffff }); 
    mesh1=new THREE.Mesh(cube,material); 
    mesh1.position.set(-2,2,0); 
    scene.add(mesh1); 

    //cube 2 
    var cube2=new THREE.BoxGeometry(2,2,2); 
    var material=new THREE.MeshBasicMaterial ({ color:0x000000 }); 
    mesh2=new THREE.Mesh(cube2,material); 
    mesh2.position.x=6; 
    mesh2.position.y=2; 
    scene.add(mesh2); 

    //cylinder 
    var cylinder=new THREE.CylinderGeometry(1,1,5,30); 
    var material=new THREE.MeshBasicMaterial({ color:0xff3399 }); 
    mesh3=new THREE.Mesh(cylinder,material); 
    mesh3.position.x=4.5; 


    mesh3.lookAt(mesh2.position); 
    mesh1.add(mesh3); 

左邊的立方體是cube1和正確的立方體是CUBE2。圓柱體是cube1的子元素,應該看起來像cube2。所以如果我移動立方體1(在y位置),圓柱體應該旋轉並且始終看着立方體2。

Here is a picture

+0

注視totate對網在空間中的矢量,在哪裏添加。 – Martin

+0

你有解決我的問題的方法嗎? – webgl

+0

mesh3.lookAt(mesh2.position.subVectors(mesh2.position,mesh1.position))?? – Martin

回答

0

LookAt旋轉朝向vector齧合在一個空間中,加入其中。

mesh2.position` is [6,2,0] 
    mesh1 position` is [-2,2,0] 

如果裏面mesh1設置mesh3.lookAt(mesh2.position)它矢量[6-2,2+2,0] = [4,4,0]將 「外觀」;

如果你想看正確的位置,你必須計算它到你的目標向量。

https://threejs.org/docs/api/math/Vector3.html

+0

謝謝你的回答,但這也不起作用。我用一張圖片更新了我的問題,也許這有助於理解我想要實現的內容。 – webgl

0

從我的角度來看,你並不需要使用對象的層次結構在這種情況下。

最好將圓柱體的位置設置爲第一個對象,然後用第二個對象的位置調用.lookAt()。

所以,讓我們想象一下,你有他們之間的物體

var cubes = []; 

和鏈接

var links = []; 

然後創建鏈接,像這樣的數組:

function linkObj(startObj, endObj) { 
    var linkGeom = new THREE.CylinderGeometry(0.12, 0.25, 1, 16); 
    linkGeom.translate(0, 0.5, 0); 
    linkGeom.rotateX(Math.PI/2); 
    var link = new THREE.Mesh(linkGeom, new THREE.MeshBasicMaterial({ 
     color: "yellow" 
    })); 
    link.userData.position = startObj; 
    link.userData.lookAt = endObj; 
    scene.add(link); 
    links.push(link); 
    } 

和鏈接對象:

linkObj(0, 1); // where 0 and 1 are indices of objects in the array 
中,你會在你的動畫循環加的lookAt的位置和點計算最終

links.forEach(function(link){ 
    link.position.copy(cubes[link.userData.position].position); 
    link.lookAt(cubes[link.userData.lookAt].position); 
    link.scale.z = cubes[link.userData.position].position.distanceTo(cubes[link.userData.lookAt].position); 
    }); 

jsfiddle例如

PS立方體的例子可以拖動