Robert
Robert

Reputation: 135

How to rotate object with camera three.js

Hi I am trying to make an abject follow the camera so I could achieve an effect of a rifle viewfinder. I am using OrbitControl. When I check camera.rotation.y it only shows that the range is from -PI/2 to PI/2 while I can rotate camera by 360 degrees. I cannot get my head around it please help!

so far I got there (it is only a part of my code):

    pivot = new THREE.Object3D();
    pivot.add(viewfinder);//adding viewfinder as a child of pivot
    scene.add( pivot );

and later on

    pivot.rotation.y =  camera.rotation.y; 

this allows to rotate my viewfinder but for some reason it is exactly by Pi/2 shifted so I deducted it from current camera position and I have this:

   pivot.rotation.y =  (camera.rotation.y - (Math.PI/2)) ;

and that allows me to rotate viewfinder with camera but only in the range of 180 degrees. How can I rotate it by full 360? Please help me. Thak You.

Upvotes: 1

Views: 3513

Answers (2)

Mohamed
Mohamed

Reputation: 11

THREE JS, I tested this with "PointerLockControls"-- IF you want OBJECT SAME Y ROTATION OF CAMERA : ** you need to do this in animation before renderer.render( scene, camera );**

const getCameraRotate = new THREE.Vector3();
        camera.getWorldDirection( getCameraRotate);
        getCameraRotate.y = 0;
        getCameraRotate.add( object.position );
        object.lookAt( getCameraRotate );

If you want OBJECT SAME X.Y.Z ROTATION OF CAMERA :

       object.rotation.copy(camera.rotation)

IF you want object same position to camera :

object.position.copy (new THREE.Vector3 (camera.position.x, camera.position.y, camera.position.z));

if your object gets the same position as the camera, you certainly wouldn't see it, because you would be inside, try to change some value, for example

new THREE.Vector3 (camera.position.x-5, camera.position .y -5, camera.position.z)

Upvotes: 1

Craig.Li
Craig.Li

Reputation: 1366

I guess you want to make the mesh always face to your camera, right? you could use camera matrix to set mesh rotation, mesh.rotation.setRotationFromMatrix(camera.matrix), but be careful if your mesh had a parent entity. or you can use lookAt() function, mesh.lookAt(camera.position), either works fine.

Upvotes: 3

Related Questions