Three.js Object3d cylinder rotation to align to a vector

后端 未结 3 1428
梦毁少年i
梦毁少年i 2020-12-13 21:39

I have searched far and wide, but can\'t seem to figure this pretty basic thing out. I have seen other examples on stackoverflow and elsewhere from a year or two ago, but t

3条回答
  •  天命终不由人
    2020-12-13 22:03

    If you have an arbitrary vector:

    var vector = new THREE.Vector3(100, 60, 20);
    

    You can align an object, such as a cylinder, to the vector like this:

    var geometry = new THREE.CylinderGeometry(2, 2, vector.length(), 4, 4);
    var mesh = new THREE.Mesh(geometry, someMaterial);
    var axis = new THREE.Vector3(0, 1, 0);
    mesh.quaternion.setFromUnitVectors(axis, vector.clone().normalize());
    

    Where axis is the original direction of the cylinder (pointing up).

    You can also move the cylinder to match the position of the vector like this:

    mesh.position.copy(vector.clone().multiplyScalar(0.5));
    

    This puts one end of the cylinder at the 0, 0, 0 and the other at 100, 60, 20, and works because I set the cylinder length to vector.length().

提交回复
热议问题