2014-07-14 47 views
1

我使用three.js創建簡單的3d矢量環境。我使用線條來表示所有3個矢量元素x,y,z和最後一個矢量表示的一條線。問題是在Windows中設置線條is not working的寬度。我試圖實現的解決方法是將一個圓柱體放置到該線上(請參見下圖中的紅色對象)。Three.js - 表示矢量的圓柱體的旋轉

這就是我目前的結果是:

three.js 3d vector lines

正如你看到的,我不能夠在氣缸旋轉到正確的位置。

我遇到了圓柱體的旋轉中心位於物體中間的問題,所以我將旋轉點移動到了圓柱體的開始處。但是,旋轉仍然無法正常工作。我想,這個軸的旋轉會相互影響。

下面是代碼:

// VEKTOR 
var vektor = {}; 
vektor._x = 2; 
vektor._y = 1.5; 
vektor._z = 1; 
vektor._length = Math.sqrt(vektor._x*vektor._x + vektor._y*vektor._y + vektor._z*vektor._z); 

// CYLINDER 
var cyl_material = new THREE.MeshBasicMaterial({ color: 0xff0000 }); 
// cylinder which is our line that represents the vector 
var cyl_width = 0.025; // default line width 
var cyl_height = vektor._length; 
// THREE.CylinderGeometry(radiusTop, radiusBottom, height, radiusSegments, heightSegments, openEnded) 
var cylGeometry = new THREE.CylinderGeometry(cyl_width, cyl_width, cyl_height, 20, 1, false); 

// translate the cylinder geometry so that the desired point within the geometry is now at the origin 
// https://stackoverflow.com/questions/12746011/three-js-how-do-i-rotate-a-cylinder-around-a-specific-point 
cylGeometry.applyMatrix(new THREE.Matrix4().makeTranslation(0, cyl_height/2, 0)); 
var cylinder = new THREE.Mesh(cylGeometry, cyl_material); 

updateCylinder(); 
scene.add(cylinder); 

而且updateCylinder改掉做旋轉的功能。

function updateCylinder() { 
    // ... stuff, then: 
    cylinder.rotation.x = Math.atan2(vektor._z,vektor._y); 
    cylinder.rotation.y = 0.5*Math.PI+Math.atan2(vektor._x,vektor._z); 
    cylinder.rotation.z = Math.atan2(vektor._x,vektor._y); 
} 

這是當前演示:http://www.matheretter.de/3d/vektoren/komponenten/

我在做什麼毛病旋轉?如何實現它以便氣缸跟隨矢量線?

感謝您的幫助。

+0

不能與數學但你已經得到了在那裏線幫助,您也許可以使用這條線來建立你的氣缸? http://threejs.org/examples/#webgl_geometry_extrude_splines 看到這個例子。如果你有一個樣條線(你的線),你可以用它來從中擠出一個圓柱體。通過這種方式,您當然可以在每次更改時都創建一個新的幾何體。但我只是想將這個添加到您的問題中,作爲一種替代方案。 – GuyGood

回答

1

如果你想使一端爲原點,向特定point另一端點改造汽缸,這裏是模式可以遵循:

首先,改變你的幾何形狀,以便一端圓柱體在原點處,而另一端(頂部)在z軸上爲正面

var geometry = new THREE.CylinderGeometry(0, 1, length, 8, 1, true); 

geometry.applyMatrix(new THREE.Matrix4().makeTranslation(0, length/2, 0)); 
geometry.applyMatrix(new THREE.Matrix4().makeRotationX(Math.PI/2)); 

然後創建你的網格,並調用lookAt()方法:

var mesh = new THREE.Mesh(geometry, material); 
mesh.lookAt(point); 

three.js所r.67

+0

太好了,謝謝。因此,我只是使用'lookAt(point)'來做3次旋轉,而'var point = new THREE.Vector3(vektor._x,vektor._y,vektor._z)'。 Math.PI/2爲什麼'makeRotationX'變得必要? –

+0

由於默認對象被認爲是「看」正z軸。在你的情況下,你需要轉換你的幾何圖形,以便「指向」這個方向。 – WestLangley