问题
I want to align one child object (the cylinder) to another object (cube2). I used the lookAt Function, but the alignment is not correct. Where is my mistake?
I have the following code:
//cube 1
var cube=new THREE.BoxGeometry(2,2,2);
var material=new THREE.MeshBasicMaterial ({ color: 0xffffff });
mesh1=new THREE.Mesh(cube,material);
mesh1.position.set(-2,2,0);
scene.add(mesh1);
//cube 2
var cube2=new THREE.BoxGeometry(2,2,2);
var material=new THREE.MeshBasicMaterial ({ color:0x000000 });
mesh2=new THREE.Mesh(cube2,material);
mesh2.position.x=6;
mesh2.position.y=2;
scene.add(mesh2);
//cylinder
var cylinder=new THREE.CylinderGeometry(1,1,5,30);
var material=new THREE.MeshBasicMaterial({ color:0xff3399 });
mesh3=new THREE.Mesh(cylinder,material);
mesh3.position.x=4.5;
mesh3.lookAt(mesh2.position);
mesh1.add(mesh3);
The left cube is cube1 and the right cube is cube2. The cylinder is the child element of cube1 and should lookAt cube2. So if I move cube 1 (in y-Position) , the cylinder should rotate and always look at cube2.
Here is a picture
回答1:
LookAt
rotate mesh towards vector
in a space, where is added.
mesh2.position` is [6,2,0]
mesh1 position` is [-2,2,0]
if you set mesh3.lookAt(mesh2.position) inside mesh1 it will "looks" on vector [6-2,2+2,0] = [4,4,0]
;
If you want to look on correct position you must calculate this to your target vector.
see https://threejs.org/docs/api/math/Vector3.html
回答2:
From my point of view, you don't need to use hierachy of objects in this case.
It's better to set position of the cylinder to the first object and then to call .lookAt() with the position of the second object.
So, let's imagine you have an array of objects
var cubes = [];
and links between them
var links = [];
then you create links, like so:
function linkObj(startObj, endObj) {
var linkGeom = new THREE.CylinderGeometry(0.12, 0.25, 1, 16);
linkGeom.translate(0, 0.5, 0);
linkGeom.rotateX(Math.PI / 2);
var link = new THREE.Mesh(linkGeom, new THREE.MeshBasicMaterial({
color: "yellow"
}));
link.userData.position = startObj;
link.userData.lookAt = endObj;
scene.add(link);
links.push(link);
}
and link objects:
linkObj(0, 1); // where 0 and 1 are indices of objects in the array
in the end you'll add calculation of position and point of lookAt in your animation loop:
links.forEach(function(link){
link.position.copy(cubes[link.userData.position].position);
link.lookAt(cubes[link.userData.lookAt].position);
link.scale.z = cubes[link.userData.position].position.distanceTo(cubes[link.userData.lookAt].position);
});
jsfiddle example
PS Cubes in the example are draggable
来源:https://stackoverflow.com/questions/41677608/three-js-lookat-function-does-not-work-correctly