Static Object in Scene - Three.js

断了今生、忘了曾经 提交于 2019-11-28 11:39:48

If you want an object -- such as crosshairs -- to be fixed in front of the camera, you can do so by adding the object as a child of the camera. Use a pattern like this one:

scene.add( camera ); // required when the camera has a child
camera.add( object );
object.position.set( 0, 0, - 100 ); // or whatever distance you want

three.js r.71

The simple way of doing this is making your object track the camera's position.

Tracking means that, at each camera update, you'll move both the camera and the object by the same amount, while keeping a fixed distance between them.

For this to work you need to set a fixed position at which your object will always be viewed, in your sample it should be (0, 0, 10).

var fixedPosition = new THREE.Vector3(0, 0, 10);

Then, in your render() function you need to update the position of the object after the camera was moved, but before you render everything.

function render() {
        controls.update();

        // let's update the object's position now!
        myMesh.position.sub(camera.position, fixedPosition);
        // now camera and mesh are at the same distance
        renderer.render(scene, camera);
        //...
    }

In this case a vector subtraction works fine, we basically take the camera's position, subtract our fixed amount (10 on the Z-axis) and you'll have that your object's position will always be positioned 10 units away from the camera on the Z-axis

In general, many of the operations you'll be doing involve 3D vectors and some math, so it's useful to understand how these operations (basic addition, subtraction, multiplication, etc.) affect what you see on screen.

If you have more doubts I suggest reading a bit about vector math, it's not too hard and you don't need to memorize formulas (Three.js implements all the math you need already), but knowing what these operations do can be incredibly useful.

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