Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Three.js line vector to cylinder?

Tags:

three.js

I have this to create a line between 2 points:

var geometry = new THREE.Geometry();
geometry.vertices.push(new THREE.Vector3(0, 0, 0));
geometry.vertices.push(new THREE.Vector3(20, 100, 55));
var line = new THREE.Line(geometry, material, parameters = { linewidth: 400 });
scene.add(line);

(The line width, does not have any effect.)

My question is how do I transform this to a cylinder? I want to create a cylinder between two points.

like image 920
Rails beginner Avatar asked Mar 09 '13 21:03

Rails beginner


2 Answers

As of December 2020:

I've tried to implement exactly what has been said in the previous responses, but nothing worked.

My solution:

cylinderMesh = function (pointX, pointY) {
   // edge from X to Y
   var direction = new THREE.Vector3().subVectors(pointY, pointX);
   const material = new THREE.MeshBasicMaterial({ color: 0x5B5B5B });
   // Make the geometry (of "direction" length)
   var geometry = new THREE.CylinderGeometry(0.04, 0.04, direction.length(), 6, 4, true);
   // shift it so one end rests on the origin
   geometry.applyMatrix(new THREE.Matrix4().makeTranslation(0, direction.length() / 2, 0));
   // rotate it the right way for lookAt to work
   geometry.applyMatrix(new THREE.Matrix4().makeRotationX(THREE.Math.degToRad(90)));
   // Make a mesh with the geometry
   var mesh = new THREE.Mesh(geometry, material);
   // Position it where we want
   mesh.position.copy(pointX);
   // And make it point to where we want
   mesh.lookAt(pointY);

   return mesh;
}
like image 86
tiagofonseca1109 Avatar answered Oct 27 '22 04:10

tiagofonseca1109


I've had the exact same problem -- in WebGL the line width is always 1. So here's a function I wrote that will take two Vector3 objects and produce a cylinder mesh:

var cylinderMesh = function( pointX, pointY )
{
    // edge from X to Y
    var direction = new THREE.Vector3().subVectors( pointY, pointX );
    var arrow = new THREE.ArrowHelper( direction, pointX );

    // cylinder: radiusAtTop, radiusAtBottom, 
    //     height, radiusSegments, heightSegments
    var edgeGeometry = new THREE.CylinderGeometry( 2, 2, direction.length(), 6, 4 );

    var edge = new THREE.Mesh( edgeGeometry, 
        new THREE.MeshBasicMaterial( { color: 0x0000ff } ) );
    edge.rotation = arrow.rotation.clone();
    edge.position = new THREE.Vector3().addVectors( pointX, direction.multiplyScalar(0.5) );
    return edge;
}
like image 25
Stemkoski Avatar answered Oct 27 '22 05:10

Stemkoski