简体   繁体   English

如何在场景中将对象添加到网格而不更改其在three.js中的位置

[英]how to add a object in scene to a mesh without changing its position in three.js

I want to keep the position of an object in scene and want to change the parent of that object from scene to any other mesh.here is a sample code http://plnkr.co/edit/fpjsUkOA0rH6FvG4DL6Z?p=preview 我想保留对象在场景中的位置,并想将该对象的父对象从场景更改为任何其他网格。这是示例代码http://plnkr.co/edit/fpjsUkOA0rH6FvG4DL6Z?p=preview

in this example when am trying to add the sphere to box it's position is changing.i want to keep the original position .try to remove comment in line 35 ,the spehere is moving towards box.i want to keep its position and make sphere box's child http://plnkr.co/edit/fpjsUkOA0rH6FvG4DL6Z?p=preview 在这个例子中,当我试图将球体添加到盒子中时,它的position正在改变。我想保持原始位置。尝试删除第35行中的注释,spehere朝着盒子移动。我想要保持其位置并使球体盒子的位置子http://plnkr.co/edit/fpjsUkOA0rH6FvG4DL6Z?p=preview

If you add the sphere to the group, you just need to substract the group's position from the sphere's position to keep it in its original world position. 如果将球体添加到组中,则只需从球体位置中减去组的位置,以使其保持在其原始世界位置即可。

  var material = new THREE.MeshLambertMaterial({color: 0x00ff00});

  var boxGeometry = new THREE.BoxGeometry(5, 15, 5);
  var box = new THREE.Mesh(boxGeometry, material);

  var sphereGeometry = new THREE.SphereGeometry( 5, 32, 32 );
  var sphere = new THREE.Mesh(sphereGeometry, material);
  sphere.position.set(0, 10, 0);
  sphere.updateMatrix();

  var group = new THREE.Object3D();
  group.translateX(6);
  group.updateMatrix();

  // if you add sphere to group object
  group.add(box);
  group.add(sphere);
  scene.add(group);

  var m = new THREE.Matrix4().getInverse(group.matrixWorld);
  sphere.applyMatrix(m);

  // if you add sphere to box
  group.add(box);
  box.add(sphere);
  scene.add(group);

  var m = new THREE.Matrix4().getInverse(box.matrixWorld);
  sphere.applyMatrix(m);

  console.log(group.position, sphere.position);

If question relies only to position then the answer of Brakebein may be correct. 如果问题仅取决于position那么Brakebein的答案可能是正确的。 But if you need also to revert scale and rotation , then you should make something like this, I think: 但是,如果您还需要还原scalerotation ,那么我应该做这样的事情:

var inversionMatrix = new THREE.Matrix4();
inversionMatrix.getInverse( parentObject.matrix );
childObject.applyMatrix(inversionMatrix);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM