Three.js - Rotation of a cylinder that represents

2019-05-29 11:06发布

问题:

I am using three.js to create a simple 3d vector environment. I am using lines to represent all 3 vector compontens x, y, z and a line for the final vector representation. Problem is that setting the width of a line is not working in Windows. The workaround that I try to implement is placing a cylinder onto the line (see red object in image below).

That is my current result:

As you see I am not able to rotate the cylinder to the correct position.

I faced the problem that the rotation center of the cylinder is in the middle of the object, so I moved the rotation point to the beginning of the cylinder. But still, rotation is not working correctly. I guess, the rotations around the axis influence each other.

Here is the code:

// 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 );  

And the function updateCylinder trys to do the rotation.

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);
}

Here is the current demo: http://www.matheretter.de/3d/vektoren/komponenten/

What am i doing wrong with the rotation? How to implement it so that the cylinder is following the vector line?

Thanks for your help.

回答1:

If you want to transform a cylinder so that one end is at the origin and the other end points toward a specific point, here is the pattern you can follow:

First, transform your geometry so one end of the cylinder is at the origin, and the other end (the top) is on the positive z-axis.

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 ) );

Then create your mesh, and call the lookAt() method:

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

three.js r.67