简体   繁体   中英

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

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

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. But if you need also to revert scale and rotation , then you should make something like this, I think:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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