Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Three.js: Rotate Cylinder into Vector3 direction

I've already searched, but didn't find anything that helps:

I got an vector and a CylinderGeometry Mesh. I want to acchieve, that the cylinder is facing the point where the vector is showing. As input I got a position (c) and a direction (m) (like a line equation: y = mx + c):

function draw (m,c, _color) {
  //... create the geometry and mesh
  // set the position
  line.position.x = c.x;
  line.position.y = c.y;
  line.position.z = c.z;

  // i've tried something like this:
  line.lookAt(c.add(m));

  //.. and add to scene
}

But it looks like the direction is the direct opposite of what I want to acchieve.

I've also tried stuff like translation:

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

and tried to get the rotation manually like line.rotation.x = direction.angleTo(vec3(1,0,0))* 180 / Math.PI;. But none of them worked like I needed.

like image 269
schlenger Avatar asked Oct 11 '25 18:10

schlenger


1 Answers

This works for me:

  // Make the geometry (of "distance" length)
  var geometry = new THREE.CylinderGeometry( 0.6, 0.6, distance, 8, 1, true );
  // shift it so one end rests on the origin
  geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, distance / 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( from.sceneObject.position );
  // And make it point to where we want
  mesh.lookAt( to.sceneObject.position );
like image 74
Leeft Avatar answered Oct 14 '25 07:10

Leeft



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!