用Three.js根据两个三维点创建Cylinder

时间:2022-06-15 05:46:38

Three.js中默认不能直接根据两个三维点的坐标创建Cylinder,创建的Cylinder默认是垂直于XOY平面的,不便于实际应用,下面是用Three.js根据两个三维点创建Cylinder:

function createCylinderMesh(x1,y1,z1,x2,y2,z2){
var x0 = (x1 + x2) / 2;
var y0 = (y1 + y2) / 2;
var z0 = (z1 + z2) / 2;
var p1 = new THREE.Vector3(x1,y1,z1);
var length = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) + (z1 - z2) * (z1 - z2));

var material = new THREE.MeshBasicMaterial( { color: 0x0000ff } );
var geometry = new THREE.CylinderGeometry(3,3,length);
geometry.applyMatrix( new THREE.Matrix4().setRotationFromEuler( new THREE.Vector3( Math.PI / 2, Math.PI, 0 ) ) );
var mesh = new THREE.Mesh(geometry,material);
mesh.position.set(x0, y0, z0);
mesh.lookAt(p1);

return mesh;
}

上面代码的关键部分是 geometry.applyMatrix( new THREE.Matrix4().setRotationFromEuler( new THREE.Vector3( Math.PI / 2, Math.PI, 0 ) ) );mesh.lookAt(p1);

其中mesh.lookAt(p1)中的p1指的是该Cylinder两个端点中的任意一个,意思是,从Cylinder的中心点朝着其中一个端点看去,自然就使得Cylinder的方向调整到正确方向了。

附图一张:

用Three.js根据两个三维点创建Cylinder