user2024875
user2024875

Reputation: 1

Get distance of two objects from camera three js

I have two squares in space which are something like front and back wall of cube one vith vertices

x=-2 y=-1138 z=-2;
x=-2 y=-1134 z=-2;
x=2 y=-1138 z=-2;
x=2 y=-1134 z=-2

second

x=-2 y=1134 z=2;
x=-2 y=1138 z=2;
x=2 y=1134 z=2;
x=2 y=1138 z=2

when I calculate distanceTo from camera like this

var point1 = this.camera.matrixWorld.getPosition().clone();
var point2 = this.mesh.cubePlane3.children[0].matrixWorld.getPosition().clone();
var distance = point1.distanceTo( point2 );  

I have always the same distance for both 20,09. These squres are rotated in space, so only rotation is changed and I would need somehow find out which wall is closer to camera to be able to do something that in cube 3 walls closer to camera are not displayed and next 3 walls are displayed.

And obviously I do not understand math behind this, for example why walls which are next to each other one have positive coordinates for y and next negative + why distance is the same value, when one is closer on z axis than second. Can you pls someone help me how I can get closer walls? Thank you

Upvotes: 0

Views: 7442

Answers (2)

user2024875
user2024875

Reputation: 1

I used computeBoundingBox with this code

    this.mesh[cubePlane[0]].children[0].geometry.computeBoundingBox();

    var position = new THREE.Vector3();
    position.sub( this.mesh[cubePlane[0]].children[0].geometry.boundingBox.max, this.mesh[cubePlane[0]].children[0].geometry.boundingBox.min );
    position.multiplyScalar( 0.5 );
    position.addSelf(this.mesh[cubePlane[0]].children[0].geometry.boundingBox.min );

    this.mesh[cubePlane[0]].children[0].matrixWorld.multiplyVector3( position );

    var point1 = this.camera.matrixWorld.getPosition().clone();
    var point2 = position;
    var distance = point1.distanceTo( point2 );

and it works so thank you for your advice :)

Upvotes: 0

gaitat
gaitat

Reputation: 12632

Each geometry has a computeBoundingBox function. So you can do: var bbox = geometry.computeBoundingBox(); for each geometry that you are interested in and then use the bbox.center() to get the center of your geometry. A much faster computation is to use the computeBoundingSphere on your geometry. Then you just compare the relation of the centers to your camera position.

Upvotes: 2

Related Questions