三.js lookAt 功能无法正常工作 [英] three.js lookAt function does not work correctly

查看:37
本文介绍了三.js lookAt 功能无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个子对象(圆柱体)与另一个对象(cube2)对齐.我使用了lookAt函数,但是对齐不正确.我的错误在哪里?

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?

我有以下代码:

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

左边的立方体是cube1,右边的立方体是cube2.圆柱体是cube1 的子元素,应该看cube2.因此,如果我移动立方体 1(在 y 位置),圆柱体应该旋转并始终看着立方体 2.

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.

这是一张图片

推荐答案

在我看来,在这种情况下,您不需要使用对象的层次结构.

From my point of view, you don't need to use hierachy of objects in this case.

最好将圆柱体的位置设置为第一个对象,然后使用第二个对象的位置调用 .lookAt().

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 = [];

以及它们之间的链接

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

和链接对象:

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 示例

示例中的 PS Cubes 是可拖动的

PS Cubes in the example are draggable

这篇关于三.js lookAt 功能无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆