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

自作多情 提交于 2021-02-06 11:09:35

问题


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 front of it. How can I do this? I've tried many different ways, but I did not succeed.

Thanks


回答1:


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.




回答2:


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.




回答3:


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




回答4:


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);
}


来源:https://stackoverflow.com/questions/17218054/how-to-put-an-object-in-front-of-camera-in-three-js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!