How to put an object in front of camera in THREE.JS?

后端 未结 4 1629
野性不改
野性不改 2021-02-09 03:47

I\'m trying to put an object in front of the camera, but have not been able to.

I\'m using the FlyControls what moves the camera, and I now want to put an object in fron

相关标签:
4条回答
  • 2021-02-09 03:56
    var cx, cy, cz, lx, ly, lz;
    
    
    
    dir.set(0,0,-1);
    dir.applyAxisAngle(0,camera.rotation.x);
    dir.applyAxisAngle(1,camera.rotation.y);
    dir.applyAxisAngle(2,camera.rotation.z);
    var dist = 100;
    
    cx = camera.position.x;
    cy = camera.position.y;
    cz = camera.position.z;
    
    lx = dir.x;
    ly = dir.y;
    lz = dir.z;
    
    
    var l;
    
    l = Math.sqrt((dist*dist)/(lx*lx+ly*ly+lz*lz));
    
    var x1, x2;
    var y1, y2;
    var z1, z2;     
    
    x1 = cx + lx*l;
    x2 = cx - lx*l;
    
    y1 = cy + ly*l;
    y2 = cy - ly*l;
    
    z1 = cz + lz*l;
    z2 = cz - lz*l;
    
    
    nanobot.position.set(x1, y1, z1 );
    

    I tried to calculate the direction vector of the direction of the camera, and then calculate the line that passes through the chamber, put a point on this line at a distance from the camera

    0 讨论(0)
  • 2021-02-09 04:01

    Here's another method - applying the quarternion of the camera to a vector (dist is how far away from the camera you want the object to be):

    var vec = new THREE.Vector3( 0, 0, -dist );
    vec.applyQuaternion( camera.quaternion );
    
    nanobot.position.copy( vec );
    

    Making the object a child of the camera didn't work for me, but this applyQuarternion method did (adapted from @WestLangley's answer here: Three.js: Get the Direction in which the Camera is Looking)

    You may wish to copy the rotation from the camera too, if you want it to always be facing the camera. And if you want to tweak the object's exact position after this, you can translateX, translateY etc.

    0 讨论(0)
  • 2021-02-09 04:02

    I'm using three.js r88 and have worked out a solution starting from what Kaspar Lee posted.

    function updatePositionForCamera(camera) {
        // fixed distance from camera to the object
        var dist = 100;
        var cwd = new THREE.Vector3();
        
        camera.getWorldDirection(cwd);
        
        cwd.multiplyScalar(dist);
        cwd.add(camera.position);
        
        myObject3D.position.set(cwd.x, cwd.y, cwd.z);
        myObject3D.setRotationFromQuaternion(camera.quaternion);
    }
    
    0 讨论(0)
  • 2021-02-09 04:23

    Have you tried making your object a child of your camera and then translating it forward?

    camera.add(nanobot);
    nanobot.position.set(0,0,-100);
    

    The above places the nanobot permanently 100 units in front of the camera... and that's where it will stay until you do:

    camera.remove(nanobot);
    

    ...at which point it should just stay where it is in global space until you move it using some other method.

    0 讨论(0)
提交回复
热议问题