Ronak Shetiya
Ronak Shetiya

Reputation: 980

looking to rotate a object by using the pivot point of another object

I have a 2 objects(A and B) which respectively have 2 positions. I am trying to revolve the object B around the object A. so my idea is to take the center of object A and Make object B to rotate around it in a circular direction and would like to know the position of B while it is revolving around

here is a graphical representation image

Upvotes: 2

Views: 112

Answers (1)

Mugen87
Mugen87

Reputation: 31026

I suggest you use an instance of THREE.Group as a pivot object. You can add object B to this object and transform it like demonstrated in the following live example.

The position of the object B in world space can be extracted from the world matrix via Vector3.setFromMatrixPosition().

let camera, scene, renderer;

let objectB, pivot;

const worldPosition = new THREE.Vector3();

init();
animate();

function init() {

  camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.01, 10);
  camera.position.z = 2;

  scene = new THREE.Scene();

  const geometry = new THREE.BoxGeometry(0.2, 0.2, 0.2);
  const material = new THREE.MeshNormalMaterial();

  const objectA = new THREE.Mesh(geometry, material);
  scene.add(objectA);

  pivot = new THREE.Group();
  scene.add(pivot);

  objectB = new THREE.Mesh(geometry, material);
  objectB.scale.setScalar(0.5);
  objectB.position.x = 1;
  pivot.add(objectB);

  renderer = new THREE.WebGLRenderer({
    antialias: true
  });
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);

}

function animate() {

  requestAnimationFrame(animate);

  pivot.rotation.y += 0.01;
    
  // pivot.updateMatrixWorld(); // ensure world matrix is up to date
    
  // console.log( worldPosition.setFromMatrixPosition( objectB.matrixWorld ) );

  renderer.render(scene, camera);

}
body {
  margin: 0;
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/three.js"></script>

Upvotes: 2

Related Questions