How can I center my object (random position, rotation) in my camera?

Hi I am new to three js and have a question regarding the camera facing the object.

I am using css3Drenderer to bring a div text box into 3D scene and I want to make my camera to view the div box in the center of the screen and upright position.

My div box position and rotatiton value are random. So my camera has to check the random value of my div box position and rotation value and look at the div box after that.

here’s how I came up with so far but it only works when with the position but when rotation value is added, the div box doesn’t align upright in my camera.

So my goal here is to view my div box perpendicular, 1000 unit far away and div box to be center of my screen.

I would appreciate any help on this! thanks a lot in advance :slight_smile:

const x = Math.random() * 1000 - 500;
const y = Math.random() * 1000 - 500;
const z = Math.random() * 1000 - 500;
cssElement.position.set(x, y, z);

const rx = Math.random() * 2 * Math.PI;
const ry = Math.random() * 2 * Math.PI;
const rz = Math.random() * 2 * Math.PI;
cssElement.rotation.set(rx, ry, rz);

scene.add(cssElement);


const offset = new THREE.Vector3(0, 0, 1000);
offset.applyQuaternion(cssElement.quaternion);
camera.position.copy(cssElement.position).add(offset);
camera.lookAt(cssElement.position);

const up = new THREE.Vector3(0, 1, 0);
up.applyQuaternion(cssElement.quaternion);
camera.up.copy(up);

If you are using OrbitControls, it may interfere with trying to manually change the camera.

To make orbitControls look at something you set its target position, so controls.target.copy( cssElement.position )

IF you’re Not using orbitcontrols, then perhaps check to make sure your camera has been scene.add( camera )
If the camera isn’t added to the scene, it will still work to be rendered through, but won’t automatically update to reflect changes in position/rotation etc.

If none of these things are in play, check back, and we can look further?

1 Like

wow it worked exactly how I wanted it to be after applying controls.target.copy(cssElement.position);

Thank you so much!

1 Like

Nice!!
Yeah… you can just change that controls.target to point to whatever you need and it becomes the pivot of orbitcontrols.

If for some reason you need to take over complete control of the camera, you can controls.enabled = false, and then control camera manually, and set it back when you want it to take over again.
It actually a pretty natural way to work with camera when you get used to it.

1 Like